我的班级层次结构如下
case class A(id: String,name:String)
object A {
implicit val reads:Reads[A] = Json.reads[A]
implicit val writes:Writes[A] = Json.writes[A]
}
class B(id:String,name:String, val other:Int,val another:Vector[String]) extends A(id,name)
object B {
implicit val reads:Reads[B] = Json.reads[B]
implicit val writes:Writes[B] = Json.writes[B]
def apply(id: String,name:String, other:Int, another:Vector[String]) = new B(id,name,other,another)
def unapply(b: B):Option[(String,String)] = Some {(b.id,b.name,b.other,b.another)}
}
序列化B时的结果仅包括其父类A
的状态,并且如下:
{
id:"some value",
name: "some other value"
}
Reads
和Writes
的配置应该是什么,以便尊重子类中的配置,并适当地序列化所有包含的键值对。我期望的结果如下:
{
id:"some value",
name: "some other value",
other: 4,
another: ["a","b"]
}
我不想花哨的自定义序列化键值对。如果只有编译器没有抱怨父类缺少读写隐式,我只会在子类B中包含读写。
答案 0 :(得分:0)
只需使用this库
sealed trait A
object A {
implicit val oformat: OFormat[A] = julienrf.json.derived.oformat(adapter = NameAdapter.snakeCase)
}
case class B(x: String, y: String) extends A {}
一切都顺利进行...老实说,Play的JSON处理方法仍然很原始-例如与Spring相比。