Json4s support for case class with trait mixin

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

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

回答1:

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 trait 

More info on FieldSerializers here: 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



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