How can I rename a field during serialization with Json4s?

十年热恋 提交于 2019-12-22 05:00:28

问题


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.

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?


回答1:


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:

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



回答2:


Your code snippet has wrongly named implicit. It should be:

implicit val formats: Formats = DefaultFormats + rename


来源:https://stackoverflow.com/questions/21690594/how-can-i-rename-a-field-during-serialization-with-json4s

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!