根据实例类型编写JSON

时间:2018-02-27 02:27:54

标签: scala playframework playframework-2.0 playframework-2.5

我在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序列化程序。尝试   为此类型实现隐式Writes或Format。

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

1 个答案:

答案 0 :(得分: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)
  }
}

// test

val father : Father = Child1("aa","aaa")
Json.toJson(father).toString() // {"name":"aa","descrip":"aaa"}