4

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

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

4

3 回答 3

5

Reads.seq()您只需要带有显式的简单 Reads[Response]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)),)
于 2016-03-25T06:39:52.893 回答
2

简单的方法可能是:

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 重新编辑的答案链接

所以,我想更多地了解如何将 json 解析为模型,并决定在 Reedit 上提问。收到了一些很酷的链接,看看:

https://www.reddit.com/r/scala/comments/4bz89a/how_to_correctly_parse_json_to_scala_case_class/

于 2016-03-24T21:56:15.303 回答
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
于 2016-03-24T15:25:29.693 回答