[Play:当类扩展case类时,不遵守JSON Writes

问题描述 投票:0回答:1

我具有以下类层次结构

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中包含读写。

scala playframework play-json
1个回答
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 {}
© www.soinside.com 2019 - 2024. All rights reserved.