Search code examples
jsonscalamixinstraitsjson4s

json4s cannot serialize case class with mixin trait


Why does this not work?

object JsonExample extends App {
  import org.json4s._
  import org.json4s.native.Serialization
  import org.json4s.native.Serialization.{read, write}
  implicit val formats = Serialization.formats(NoTypeHints)

  case class Winner(id: Long, numbers: List[Int])    

  trait Greet { val greeting = "hi"}
  val obj = new Winner(1, List(1,2)) with Greet
  println(write(obj))
}

This prints an empty JSON object

{}

Whereas if I remove the "with Greet" I obtain the (correct) result:

{"id":1,"numbers":[1,2]}

Solution

  • It looks like if you are more specific with the formats you can get the result you"re after:

    import org.json4s.{FieldSerializer, DefaultFormats}
    import org.json4s.native.Serialization.write
    
    case class Winner(id: Long, numbers: List[Int])
    trait Greet { val greeting = "hi"}
    
    implicit val formats = DefaultFormats + FieldSerializer[Winner with Greet]()
    
    val obj = new Winner(1, List(1,2)) with Greet
    
    //returns {"greeting":"hi","id":1,"numbers":[1,2]}
    write(obj)