'Contextual deserialization of a field based on multiple fields?

Can CustomSerializer perform deserialization of one field based on the value in another field? In all the examples I've seen, each field is deserialized independently without any context.

Consider a case class for StreetAddress

case class StreetAddress(
    addressLine1: Option[String] = None,
    addressLine2: Option[String] = None,
    city: Option[String] = None,
    state: Option[StateCode] = None,
    zipcode: Option[String] = None,
    country: Option[CountryCode] = None
)

Currently the CustomSerializer for StateCode looks like this

class StateCodeSerializer
    extends CustomSerializer[StateCode](
        implicit formats =>
            ({
                case JString(s) =>
                    StateCode(s).getOrElse(
                    throw new IllegalArgumentException(s"Invalid state code: $s")
              )
            case JInt(i) =>
              StateCode(i.toInt).getOrElse(
                throw new IllegalArgumentException(s"Invalid state code: $i")
              )
          }, {
            case x: StateCode =>
                JString(x.toString)
        })
    )

The deserializer for StateCode needs to know the CountryCode as well because states across several countries can share the same StateCode string. Ex: "CA" is California in US as well Cadiz in Spain.

Is it possible for StateCodeSerializer to be aware of what the value of country is in the JSON?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source