How to rename a field during serialization using Json4s?

How to easily rename field names in json4s? From their documentation, I tried the following snippet, but it didn't seem to rename the field serialto id.

case class Person(serial: Int, firstName: String)

val rename = FieldSerializer[Person](renameTo("serial", "id"))

implicit val format = DefaultFormats + rename

write(Person(1, "Guest")) //returns {"serial":1,"firstName":"Guest"}

With the Jackson Library, this is pretty easy by annotating. But I'm looking for a clean scala library / solution. Is there a better library or way to serialize an object to json in scala with easy field renaming?

+5
source share
2 answers

The code you have returns the correct JSON with idas a field. Here is a slightly more detailed example for evaluation in the console:

import org.json4s._
import org.json4s.FieldSerializer._
import org.json4s.jackson.Serialization.write

case class Person(serial: Int, firstName: String)
val rename = FieldSerializer[Person](renameTo("serial", "id"))
implicit val format: Formats = DefaultFormats + rename
write(Person(1, "Guest")) // actually returns {"id":1,"firstName":"Guest"}
+6
source

. :

implicit val formats: Formats = DefaultFormats + rename
0

Source: https://habr.com/ru/post/1526262/


All Articles