10

我有这个:

package models

import play.api.libs.json._
import play.api.libs.functional.syntax._

object ModelWrites {
    implicit val tmoWrites= Json.writes[TestModelObject]
    implicit val ihWrites = Json.writes[IntHolder]
}

case class TestModelObject(s1:String, s2:String)

case class IntHolder(i1:Int, i2:Int)

trait HasInts {
    val ints: List[IntHolder]
}

当我这样做时:

scala> val tmo = new TestModelObject("hello", "world") with HasInts {
  val ints = List(IntHolder(1,2), IntHolder(3,4))
}

scala> Json.toJson(tmo)
res0: play.api.libs.json.JsValue = {"s1":"hello","s2":"world"}

如何隐式序列化混合的 val 'ints'?喜欢:

scala> val someInts = List(IntHolder(8,9), IntHolder(10,11))
someInts: List[models.IntHolder] = List(IntHolder(8,9), IntHolder(10,11))

scala> Json.toJson(someInts)
res1: play.api.libs.json.JsValue = [{"i1":8,"i2":9},{"i1":10,"i2":11}]

注意:如果我尝试:implicit val hasIntsWrites = Json.writes[HasInts] 我(预期?)得到:

[error] Models.scala:10: No unapply function found
[error]     implicit val hasIntsWrites = Json.writes[HasInts]
[error]                                             ^
4

1 回答 1

9

您将无法在此处直接使用实验性的“Inception”功能( Json.writes[...]),因为它仅适用于案例类。但是,您可以在 Inception 的实例Writes上构建提供的实例的基础上构建,只需很少的样板即可完成您想要的事情。

请注意,我忽略了这样的问题:在实例化这样的案例类时混合特征是否是一个好主意——它可能不是——但我在这里给出的方法也适用于更一般的情况。

首先是类和导入(这里没有变化):

case class TestModelObject(s1: String, s2: String)
case class IntHolder(i1: Int, i2: Int)
trait HasInts { val ints: List[IntHolder] }

import play.api.libs.json._
import play.api.libs.functional.syntax._

现在我们需要将所有优先级较低的实例放入一个特征中,以确保编译器会选择正确的实例,因为TestModelObject with HasInts它是TestModelObjectand的子类型HasInts

trait LowPriorityWritesInstances {
  implicit val tmoWrites = Json.writes[TestModelObject]
  implicit val ihWrites = Json.writes[IntHolder]

  implicit object hiWrites extends OWrites[HasInts] {
    def writes(hi: HasInts) = Json.obj("ints" -> hi.ints)
  }
}

现在主要事件:

object WritesInstances extends LowPriorityWritesInstances {
  implicit val tmowhiWrites = new Writes[TestModelObject with HasInts] {
    def writes(o: TestModelObject with HasInts) =
      tmoWrites.writes(o) ++ implicitly[OWrites[HasInts]].writes(o)
  }
}

我们完成了:

scala> import WritesInstances._
import WritesInstances._

scala> val tmo = new TestModelObject("hello", "world") with HasInts {
     |   val ints = List(IntHolder(1, 2), IntHolder(3, 4))
     | }

scala> println(Json.toJson(tmo))
{"s1":"hello","s2":"world","ints":[{"i1":1,"i2":2},{"i1":3,"i2":4}]}

如预期的。

于 2013-01-03T20:55:00.563 回答