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?
您只需要简单的 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)
归档时间: |
|
查看次数: |
3661 次 |
最近记录: |