根据实例类型编写JSON

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

我在Play for Scala中有以下类结构:

sealed trait Father
final case class Child1 (name: String, descrip: String) extends Father
final case class Child2 (age: Int, price: Int) extends Father

case class MyClass (someValue: Int, father: Father)

现在,我需要为MyClass定义隐式JSON函数:

  implicit val myClassWrite : Writes[MyClass] = (
     (JsPath \ "some").write[Int] and
     (JsPath \ "father").write[Father]
  ) (unlift(MyClass.unapply)) 

我得到的是:

找不到类型为父的Json序列化程序。尝试为此类型实现隐式写入或格式。

问题是没有办法为Father编写一个Writes JSON函数,因为它是一个没有属性的特征。我只能为Child1Child2编写JSON函数,但我仍然得到错误。我的目的是让Play根据实例类型插入Child1Child2的JSON。 Play可以做些什么吗?

scala playframework playframework-2.0 playframework-2.5
1个回答
2
投票
implicit val c1 = Json.format[Child1]
implicit val c2 = Json.format[Child2]

implicit val fatherWrites = new Writes[Father] {
  override def writes(o: Father) = o match {
    case x: Child1 => c1.writes(x)
    case x: Child2 => c2.writes(x)
  }
}

//测试

val father : Father = Child1("aa","aaa")
Json.toJson(father).toString() // {"name":"aa","descrip":"aaa"}
© www.soinside.com 2019 - 2024. All rights reserved.