简体   繁体   中英

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

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)

I guess that it uses Greet type instead of Winner. However I don't know how you could solve it (except with a custom format maybe). Otherwise you could try Genson , it works nicely with your example and doesn't require tons of imports:

import com.owlike.genson.defaultGenson_

// produces {"id":1,"numbers":[1,2]}
val jsonString = toJson(winnerObject)

It also supports json4s types, so you can for example still deser to any JValue subclass if you want a DOM like representation and use json4s from there.

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