为JSON集合类型定义`Reads` [英] Defining `Reads` for JSON Set Type

查看:195
本文介绍了为JSON集合类型定义`Reads`的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create a play.api.libs.Reads for my People case class?

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)

推荐答案

(...)(People)语法专为您构建带有以下参数的列表(从技术上讲,它是Builder,而不是列表)而设计and,并想将People构造函数提升到Reads的应用函子中,以便可以将其应用于这些参数.

The (...)(People) syntax is designed for when you've built up a list of arguments (well, technically it's a Builder, not a list) with and and want to lift the People constructor into the applicative functor for Reads so that you can apply it to those arguments.

例如,如果您的People类型看起来像这样:

For example, if your People type looked like this:

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]].

In your case, though, the constructor for People has a single argument, and you haven't used and, so you don't have a Builder[Reads[Set[Id] ~ String], you've just got a plain old Reads[Set[Id]].

这很好,因为它意味着您不需要怪异的应用函子语法-您只需要map:

This is nice, because it means you don't need the weird applicative functor syntax—all you need is map:

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

您完成了.

这篇关于为JSON集合类型定义`Reads`的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆