简体   繁体   中英

Json4s support for case class with trait mixin

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM