我正在使用implicit val reads
映射Json,如:
{
"id": 1
"friends": [
{
"id": 1,
"since": ...
},
{
"id": 2,
"since": ...
},
{
"id": 3,
"since": ...
}
]
}
到案例类
case class Response(id: Long, friend_ids: Seq[Long])
我只能使用反映JSON friends
结构的中间类。但我从来没有在我的应用程序中使用它。有没有办法编写Reads[Response]
对象,以便我的Response类直接映射到给定的JSON?
答案 0 :(得分:4)
您只需要对Reads.seq()
使用明确的friend_ids
进行简单的阅读[回复],例如
val r: Reads[Response] = (
(__ \ "id").read[Long] and
(__ \ "friends").read[Seq[Long]](Reads.seq((__ \ "id").read[Long]))
)(Response.apply _)
结果将是:
r.reads(json)
scala> res2: play.api.libs.json.JsResult[Response] = JsSuccess(Response(1,List(1, 2, 3)),)
答案 1 :(得分:1)
您可以尝试以下
@annotation.tailrec
def go(json: Seq[JsValue], parsed: Seq[Long]): JsResult[Seq[Long]] =
json.headOption match {
case Some(o @ JsObject(_)) => (o \ "id").validate[Long] match {
case JsError(cause) => JsError(cause)
case JsSuccess(id) => go(json.tail, parsed :+ id)
}
case Some(js) => JsError(s"invalid friend JSON (expected JsObject): $js")
case _ => JsSuccess(parsed) // nothing more to read (success)
}
implicit val friendIdReader = Reads[Seq[Long]] {
case JsArray(values) => go(values, Nil)
case json => JsError(s"unexpected JSON: $json")
}
implicit val responseReader = Json.reads[Response]
// responseReader will use friendIdReader as Reads[Seq[Long]],
// for the property friend_ids
答案 2 :(得分:1)
简单的方法可能是:
import play.api.libs.functional.syntax._
import play.api.libs.json.{JsValue, Json, _}
case class Response(id: Long, friend_ids: Seq[Friends])
object Response {
implicit val userReads: Reads[Response] = (
(JsPath \ "id").read[Long] and
(JsPath \ "friends").read[Seq[Friends]]
) (Response.apply _)
}
case class Friends(id: Long, since: String)
object Friends {
implicit val fmt = Json.format[Friends]
}
没有case class Friends
我发现难以找到解决方案,但如果我找到一个解决方案就会发布
编辑:添加了关于Scala reedit的答案链接
所以,我想更多地了解如何将json解析为模型,并决定询问Reedit。收到一些非常酷的链接,看看:
https://www.reddit.com/r/scala/comments/4bz89a/how_to_correctly_parse_json_to_scala_case_class/