How can I rename a field during serialization with Json4s?

时间:2022-01-07 20:18:00

How to easily rename field-names in json4s? From their documentation, i've tried the following snippet but it doesn't seem to rename the serial field to id.

如何在json4s中轻松重命名字段名?从他们的文档,我已经尝试了以下代码片段,但它似乎没有将序列字段重命名为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 Jackson library, it's pretty easy by declaring an annotation. But i'm looking for a pure scala library/solution. Is there a better library or way for object-to-json serialization in scala with easy field-renaming?

使用Jackson库,通过声明注释非常简单。但我正在寻找一个纯粹的scala库/解决方案。是否有更好的库或方法用于scala中的对象到json序列化,并且易于字段重命名?

1 个解决方案

#1


5  

The code you have is returning the correct JSON with id as a field. Here is a slightly fuller example to evaluate in the console:

您拥有的代码是返回正确的JSON,其id为字段。这是在控制台中评估的一个稍微更全面的示例:

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"}

#1


5  

The code you have is returning the correct JSON with id as a field. Here is a slightly fuller example to evaluate in the console:

您拥有的代码是返回正确的JSON,其id为字段。这是在控制台中评估的一个稍微更全面的示例:

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"}