为JSON集类型定义`Reads`

时间:2014-01-30 16:10:46

标签: json scala playframework playframework-json

如何为play.api.libs.Reads案例类创建People

scala> type Id = Long
defined type alias Id

scala> case class People(names: Set[Id])
defined class People

scala>   implicit val PeopleReads: Reads[People] = (
     |     (__ \ "names").read[Set[Id]])(People)
<console>:21: error: overloaded method value read with alternatives:
  (t: Set[Id])play.api.libs.json.Reads[Set[Id]] <and>
  (implicit r: play.api.libs.json.Reads[Set[Id]])play.api.libs.json.Reads[Set[Id]]
 cannot be applied to (People.type)
           (__ \ "names").read[Set[Id]])(People)

1 个答案:

答案 0 :(得分:3)

(...)(People)语法是为您构建一个参数列表而设计的(好的,技术上它是Builder,而不是列表)and并且想要提升将People构造函数放入Reads的applicative functor中,以便将其应用于这些参数。

例如,如果您的People类型如下所示:

case class People(names: Set[Id], home: String)

你可以写:

implicit val PeopleReads: Reads[People] = (
  (__ \ "names").read[Set[Id]] and
  (__ \ "home").read[String]
)(People)

但是,在你的情况下,People的构造函数只有一个参数,而你没有使用and,所以你没有Builder[Reads[Set[Id] ~ String],你就是只有一个普通的Reads[Set[Id]]

这很好,因为这意味着你不需要奇怪的应用程序仿函数语法 - 你需要的只是map

implicit val PeopleReads = (__ \ "names").read[Set[Id]].map(People)

你已经完成了。