为JSON集类型定义“Reads”

为JSON集类型定义“Reads”,json,scala,playframework,playframework-json,Json,Scala,Playframework,Playframework Json,如何为我的人物案例类创建play.api.libs.Reads 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)

如何为我的
人物
案例类创建
play.api.libs.Reads

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)
scala>type Id=Long
定义的类型别名Id
scala>案例类人员(姓名:Set[Id])
界定阶级的人
scala>隐式val PeopleReads:Reads[People]=(
|(u \“姓名”)。阅读[设置[Id]](人物)
:21:错误:使用可选项读取重载方法值:
(t:Set[Id])play.api.libs.json.Reads[Set[Id]]
(隐式r:play.api.libs.json.Reads[Set[Id]])play.api.libs.json.Reads[Set[Id]]
无法应用于(People.type)
(u \“姓名”)。阅读[设置[Id]](人物)
当你用
建立了一个参数列表(从技术上讲,它是一个
生成器,而不是一个列表),并且想要将
构造函数提升到应用函数中,以便
读取
,这样你就可以将它应用到那些参数中时,就可以使用
语法了

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

case class People(names: Set[Id], home: String)
你可以写:

implicit val PeopleReads: Reads[People] = (
  (__ \ "names").read[Set[Id]] and
  (__ \ "home").read[String]
)(People)
不过,在您的例子中,
人员的构造函数只有一个参数,而您没有使用
,因此您没有
生成器[Reads[Set[Id]~String]
,您只有一个普通的
Reads[Set[Id]]

这很好,因为这意味着您不需要奇怪的应用程序函子语法,您只需要
map

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

你完成了。

JsPath
一样吗?如果是,你更喜欢
吗?如果是,为什么?是的,它只是一个别名,旨在提供一种特定的DSL。就我个人而言,这不是我通常喜欢的那种东西,但我恰好非常喜欢这种情况下的语法。我认为没有除此之外,你可以接受它或离开它。你可以说更多关于
…阅读[Set[Id].map(People)
?map(People)
函数的签名是什么?我知道
People
是一个case类,但我理解map:
M[a]。map(a=>B):M[B]
这只是
人的简写。应用
,或者
(Id:Set[Id])=>人(Id)
。谢谢你,特拉维斯。另外,你能告诉我如何为人编写
吗?我试过
隐式val PeopleWrites:Writes[People]=(JsPath\“names”)。写[Set[Int]]。映射(unlift(x=>一些((x.names))
,但失败了。