在使用Json4s进行序列化期间,如何重命名字段? [英] How can I rename a field during serialization with Json4s?

查看:221
本文介绍了在使用Json4s进行序列化期间,如何重命名字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何轻松重命名json4s中的字段名?从他们的文档中,我尝试了以下代码段,但似乎没有将serial字段重命名为id.

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

使用Jackson库,通过声明批注非常容易.但是我正在寻找一个纯Scala库/解决方案.在scala中,是否有一种更好的库或方法可以通过简单的字段重命名在scala中进行对象到json的序列化?

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?

推荐答案

您拥有的代码将id作为字段返回正确的JSON.这是在控制台中评估的一个更完整的示例:

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

这篇关于在使用Json4s进行序列化期间,如何重命名字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆