GammaVega
GammaVega

Reputation: 779

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

Upvotes: 3

Views: 800

Answers (1)

Nick Cecil
Nick Cecil

Reputation: 2950

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

Upvotes: 2

Related Questions