我具有以下类层次结构
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中包含读写。
只需使用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 {}