Search code examples
scalajson4s

How to rename nested fields with Json4s


As the title states, I am trying to rename fields on generated json from case classes using Json4s.

If I try to rename fields on simple case classes like:

case class User(name: String, lastName: String)

Following examples that you can find in the documentation of json4s or here How can I rename a field during serialization with Json4s? will work.

But documentation does not mention how to do nested object renames like for example from deviceId to did in this example:

case class User(name: String, lastName: String, details: UserDetails)
case class UserDetails(deviceId: String)

I tried using things like:

FieldSerializer.renameFrom("deviceId", "did")

or

FieldSerializer.renameFrom("details.deviceId", "details.did")

or

parse(message) transformField {
  case ("deviceId", value) => ("did", value)
}

or

parse(message) transformField {
  case ("details.deviceId", value) => ("details.did", value)
}

And none of them worked, so my question is: Is this nested rename possible on scala4s? If yes, how can I do to for example rename deviceId to did?


Solution

  • For the nested object, you can create FieldSerializer to bind this nested type, like:

      import org.json4s._
      import org.json4s.FieldSerializer._
      import org.json4s.jackson.Serialization.write
      val rename = FieldSerializer[UserDetails](renameTo("deviceId", "did")) // bind UserDetails to FieldSerializer
      implicit val format: Formats = DefaultFormats + rename
      println(write(u))
      > {"name":"name","lastName":"lastName","details":{"did":"deviceId"}}