我正在尝试使用 json4s 和 jackson 支持序列化 scala case 类.但是对于我尝试混合特征的场景,它无法序列化类.下面是一个代码示例.
trait ISearchKey {var id:String = ""}当我执行下面的代码时,我得到空的大括号,没有序列化的值,但是如果我删除 trait mixin,那么 CrystalFieldInfo 值就会正确序列化
val fld = new CrystalFieldInfo("Field1") with ISearchKeyfld.id = "Id1"隐式 val 格式 = Serialization.formats(NoTypeHints)val ser = write[CrystalFieldInfo with ISearchKey](fld)打印(系列)如果您对此问题有任何见解,我们将不胜感激.提前致谢
解决方案为了让 Json4s 序列化的不仅仅是 case 类成员变量,你需要为你的 trait 添加一个 FieldSerializer 到你的格式变量,像这样:
隐式 val 格式 = DefaultFormats + FieldSerializer[ISearchKey]()val ser = write[CrystalFieldInfo with ISearchKey]println(ser)//应该包含 ISearchKey trait 中的id"字段关于 FieldSerializers 的更多信息在这里:github/json4s/json4s#serializing-fields-of-a-class
源码中还有几个例子:github/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala
I am trying to serialize scala case class using json4s with jackson support. But for scenarios where i am trying to mixin traits, it fails to serialize the class. Below is a code example.
trait ISearchKey { var id:String = "" }When i execute below code i get empty curly brackets, no value serialized, but if i remove trait mixin then CrystalFieldInfo value gets serialized properly
val fld = new CrystalFieldInfo("Field1") with ISearchKey fld.id = "Id1" implicit val formats = Serialization.formats(NoTypeHints) val ser = write[CrystalFieldInfo with ISearchKey](fld) println(ser)Would appreciate any insight into this problem. Thanks in advance
解决方案To make Json4s serialize more than just case class member variables, you need to add a FieldSerializer for your trait to your formats variable, like so:
implicit val formats = DefaultFormats + FieldSerializer[ISearchKey]() val ser = write[CrystalFieldInfo with ISearchKey] println(ser) // should include the "id" field from the ISearchKey traitMore info on FieldSerializers here: github/json4s/json4s#serializing-fields-of-a-class
There are also several examples in the source: github/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala
更多推荐
Json4s 支持带有特征混合的案例类
发布评论