Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Contextual deserialization of a field based on multiple fields? #1022

Open
apadakan-livongo opened this issue Feb 22, 2022 · 0 comments
Open

Comments

@apadakan-livongo
Copy link

apadakan-livongo commented Feb 22, 2022

json4s version

3.6.7

scala version

2.12

jdk version

11

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 as Cadiz in Spain.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

No branches or pull requests

1 participant