【问题标题】:Writing JSON depending on instance type根据实例类型编写 JSON
【发布时间】:2018-08-06 14:20:44
【问题描述】:

我在 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 编写写入 JSON 函数,因为它是一个没有属性的特征。我只能为Child1 和Child2 编写JSON 函数,但我仍然得到错误。我的意图是让 Play 根据实例类型插入 Child1 或 Child2 的 JSON。这是 Play 能做到的吗?

【问题讨论】:

  • 播放 JSON 可以直接为 seal trait 生成 writer。

标签: scala playframework playframework-2.0 playframework-2.5


【解决方案1】:
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"}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多