播放:当类扩展案例类时,不遵守JSON Writes

时间:2019-11-12 16:04:14

标签: scala playframework play-json

我的班级层次结构如下

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

ReadsWrites的配置应该是什么,以便尊重子类中的配置,并适当地序列化所有包含的键值对。我期望的结果如下:

{
  id:"some value",
  name: "some other value",
  other: 4,
  another: ["a","b"]
}

我不想花哨的自定义序列化键值对。如果只有编译器没有抱怨父类缺少读写隐式,我只会在子类B中包含读写。

1 个答案:

答案 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相比。