[英]Json4s support for case class with trait mixin
I am trying to serialize scala case class using json4s with jackson support. 我正在尝试使用带有jackson支持的json4s序列化scala案例类。 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 当我执行下面的代码时,我得到空的大括号,没有值序列化,但如果我删除特征mixin然后CrystalFieldInfo值被正确序列化
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: 要使Json4s序列化不仅仅是case类成员变量,你需要为你的format变量添加一个FieldSerializer,如下所示:
implicit val formats = DefaultFormats + FieldSerializer[ISearchKey]()
val ser = write[CrystalFieldInfo with ISearchKey]
println(ser) // should include the "id" field from the ISearchKey trait
More info on FieldSerializers here: https://github.com/json4s/json4s#serializing-fields-of-a-class 有关FieldSerializers的更多信息,请访问: https : //github.com/json4s/json4s#serializing-fields-of-a-class
There are also several examples in the source: https://github.com/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala 源代码中还有几个例子: https : //github.com/json4s/json4s/blob/ebc76d70309c79c39df4be65f16b88d208f47055/tests/src/test/scala/org/json4s/native/FieldSerializerExamples.scala
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.