Home > OS >  Scala - Use uppercase first letter when decoding Json values with Zio JSON
Scala - Use uppercase first letter when decoding Json values with Zio JSON

Time:09-19

I'm using Zio Json library to attempt to decode the following:

object BasicInfo {
    private case class BasicInfoWire(
      defaultPaymentMethod: DefaultPaymentMethod,
      IdentityId__c: String,
      sfContactId__c: String,
      balance: BigDecimal,
      currency: String
    )

    given JsonDecoder[BasicInfo] = DeriveJsonDecoder.gen[BasicInfoWire].map {
      case BasicInfoWire(defaultPaymentMethod, IdentityId__c, sfContactId__c, balance, currency) =>
        IdentityId__c match {
          case "" => BasicInfo(defaultPaymentMethod, None, sfContactId__c, (balance.toDouble * 100).toInt, currency)
          case id => BasicInfo(defaultPaymentMethod, Some(id), sfContactId__c, (balance.toDouble * 100).toInt, currency)
        }
    }
  }

As Scala doesn't allow variable names to start with uppercase, I'm getting a Not Found error when referring to the variable inside the case statement.

How can I amend this to make it work?

CodePudding user response:

object BasicInfo {
    private case class BasicInfoWire(
      defaultPaymentMethod: DefaultPaymentMethod,
      IdentityId__c: String,
      sfContactId__c: String,
      balance: BigDecimal,
      currency: String
    )

    given JsonDecoder[BasicInfo] = DeriveJsonDecoder.gen[BasicInfoWire].map {
      case BasicInfoWire(defaultPaymentMethod, identityId, sfContactId__c, balance, currency) =>
        identityId match {
          case "" => BasicInfo(defaultPaymentMethod, None, sfContactId__c, (balance.toDouble * 100).toInt, currency)
          case id => BasicInfo(defaultPaymentMethod, Some(id), sfContactId__c, (balance.toDouble * 100).toInt, currency)
        }
    }
  }

Solved it with this.

  • Related