为列表创建读数[案例类]

时间:2014-02-06 22:04:08

标签: json scala playframework

我有3个案例类:

scala> case class Friend(id: Long, hobbies: List[Long])
defined class Friend

scala> case class Kid(friends: List[Friend])
defined class Kid

scala> case class Parent(kids: List[Kid])
defined class Parent

他们可以通过层次结构显示(父母有孩子有朋友(id和爱好)。

Parent   
   ---> Kid
      ---> Friend
           ---> id: Long
           ---> hobbies: List[Long]

我创建了FriendsReads(即使senia指出here,我也可以使用

scala> implicit val FriendReads: Reads[Friend] = Json.format[Friend]
FriendReads: play.api.libs.json.Reads[Friend] = play.api.libs.json.OFormat$$anon$1@236b2692

scala> implicit val FriendReads: Reads[Friend] = (
     |   (JsPath \ "id").read[Long] and
     |    (JsPath \ "hobbies").read[List[Long]]
     | )(Friend.apply _)
FriendReads: play.api.libs.json.Reads[Friend] = play.api.libs.json.Reads$$anon$8@4bb7bb4

然后,当我尝试创建KidReads时,我遇到了编译时问题。

scala> implicit val KidReads: Reads[Kid] = (
     |   (JsPath \ "friends").read[List[Friend]]
     | )(Kid.apply _)
<console>:40: error: overloaded method value read with alternatives:
  (t: List[Friend])play.api.libs.json.Reads[List[Friend]] <and>
  (implicit r: play.api.libs.json.Reads[List[Friend]])play.api.libs.json.Reads[List[Friend]]
 cannot be applied to (List[Friend] => Kid)
         (JsPath \ "friends").read[List[Friend]]
                              ^

如何解决此错误?

1 个答案:

答案 0 :(得分:1)

表达式(JsPath \ "friends").read[List[Friend]]创建Reads[List[Friend]],您可以使用Reads[Kid]方法将其转换为map,如下所示:

implicit val KidReads: Reads[Kid] =
  (JsPath \ "friends").read[List[Friend]] map Kid.apply

功能Kid.apply将应用于Reads[List[Friend]]#reads的结果,如下所示:

val friendListReads: Reads[List[Friend]] = (JsPath \ "friends").read[List[Friend]]

implicit val kidReads: Reads[Kid] = new Reads[Kid] {
  def reads(json: JsValue): JsResult[Kid] = friendListReads.reads(json) match {
    case JsSuccess(fList, path) = JsSuccess(Kid(fList), path)
    case e: JsError => e
  }
}