单一路径的编译器错误 Reads[T]

Compiler error Reads[T] for single path

Play 2.5.x 文档没有提供示例,我可以使用它来尝试通过为我的模型定义隐式 Reads[T] 来解决我的问题。

有人可以指出我做错了什么吗?

我的模特:

case class Entry(id: Int, typ: String, caught: ZonedDateTime)
case class Data(entries: Seq[Entry])

Entry类型下面的Reads就可以了

 implicit val entryReads: Reads[Entry] = (
      (__ \ "id").read[Int] and
      (__ \ "typ").read[String] and
      (__ \ "caught").read[ZonedDateTime]
    )(Entry.apply _)

问题

在我下面的Reads[Data]。编译器抱怨它需要数据而不是条目。

找到:Reads[api.test.Entry] 需要:Reads[api.test.Data]

implicit val dataReads: Reads[Data] = (JsPath \ "entries").read[Seq[Entry]]

如果我修改 Data 使其具有多个字段。

case class Data(entries: Seq[Entry], someStr: String)

然后我的 dataReads 使用组合器编译正常。

 implicit val dataReads: Reads[Data] = (
      (__ \ "entries").read[Seq[Entry]] and
      (__ \ "someStr").read[String]
    )(Data.apply _)

问题是我的数据并不真正需要那个字符串。

Play 文档包含大量定义隐式 Reads/Writes 的示例,这些示例为具有多个字段但 none 具有单个字段的案例 类。

看看地图。

implicit val dataReads: Reads[Data] = (
        (__ \ "entries").read[Seq[Entry]].map(Data(_))
    )

如果您还需要定义 Writes[T],您可能对此 post 感兴趣 - How to write a Play JSON writes converter for a case class with a single nullable member

如果使用乘法字段,则使用函数语法和 FunctionalBuilder.apply 函数,它填充 Data.apply 个参数:

implicit val dataReads: Reads[Data] = (... and ...)(Data.apply _)

一样

val dataBuilder: FunctionalBuilder[Reads]#CanBuild2[Seq[Entry], String] = (... and ...)

implicit val dataReads: Reads[Data] = dataBuilder(Data.apply _)

对于一个字段没有使用Reads函数语法,所以你必须自己填写Data.apply参数,映射(__ \ "entries")Data.entries

implicit val dataReads: Reads[Data] = (
  (__ \ "entries").read[Seq[Entry]].map(Data)
)