[英]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 这将打印一个空的JSON对象
{}
Whereas if I remove the "with Greet" I obtain the (correct) result: 而如果我删除“ with Greet”,则会得到(正确)结果:
{"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. 我猜它使用的是Greet类型而不是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:
否则,您可以尝试Genson ,它可以很好地配合您的示例,并且不需要大量的进口:
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. 它还支持json4s类型,因此,例如,如果您想要DOM之类的表示形式并从那里使用json4s,则仍然可以使用JValue子类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.