scala play 读取解析嵌套的 json

rom*_*man 4 json scala playframework playframework-2.0 playframework-json

我使用implicit val reads映射 Json 像:

{
   "id": 1
   "friends": [
    {
      "id": 1,
      "since": ...
    },
    {
      "id": 2,
      "since": ...
    },
    {
      "id": 3,
      "since": ...
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

到案例类

case class Response(id: Long, friend_ids: Seq[Long])
Run Code Online (Sandbox Code Playgroud)

我只能让它与反映 JSONfriends结构的中间类一起工作。但我从来没有在我的应用程序中使用它。有没有办法编写一个Reads[Response]对象,以便我的 Response 类可以直接映射到给定的 JSON?

and*_*niy 5

您只需要简单的 Reads[Response] 与明确Reads.seq()friend_ids例如

val r: Reads[Response] = (
  (__ \ "id").read[Long] and
    (__ \ "friends").read[Seq[Long]](Reads.seq((__ \ "id").read[Long]))
  )(Response.apply _)
Run Code Online (Sandbox Code Playgroud)

结果将是:

r.reads(json)

scala> res2: play.api.libs.json.JsResult[Response] = JsSuccess(Response(1,List(1, 2, 3)),)
Run Code Online (Sandbox Code Playgroud)