Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json4s support for case class with trait mixin

Tags:

scala

json4s

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

like image 419
GammaVega Avatar asked Dec 01 '25 07:12

GammaVega


1 Answers

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

like image 185
Nick Cecil Avatar answered Dec 03 '25 21:12

Nick Cecil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!