正在处理 JSON Scala 播放 WS 中的响应

Processing JSON Response in Scala play WS

我想处理以下 JSON 响应:

[ 
   { 
      "name":"xxx1",
      "format":"xxx2",
      "type":"xxx3",
      "url":"xxx4"
   },
   { 
      "name":"yyy1",
      "format":"yyy2",
      "type":"yyy3",
      "url":"yyy4"
   }
]

正准备写相关代码,卡在这里:

  case class Repository(repoName: String, repoFormat: String, repoType: String, repoURL: String)
  case class RepositoryList(repositoryList: List[Repository])

  implicit val repoReads = Reads[Repository] = (
    (JsPath \ "name").read[String] and
      (JsPath \ "format").read[String] and
      (JsPath \ "type").read[String] and
      (JsPath \ "url").read[String]
  )(Repository.apply _)

  implicit val repoListReads = Reads[RepositoryList] = (
    (???).read[Seq[Repository]]
  )(RepositoryList.apply _)

request.get().map(response => Ok((response.json).validate[RepositoryList]))

“???”是怎么回事?部分?它基本上是一个 JSON 的列表,没有那个级别的属性。

提前致谢!

实用的解决方案是使用 List[Repository] 然后创建一个 RepositoryList:

request.get()
   .map(response => 
        Ok(
           (response.json).validate[List[Repository]]
              .map(RepositoryList)
        )
    )

勾选scalafiddle

就使用 validate[RepositoryList] 和避免验证后的额外映射而言,使用 Reads.list 组合可以解决问题。所以 ???可以替换为

implicit val repoListReads: Reads[RepositoryList] = Reads.list[Repository].map(RepositoryList)

你可以打电话 response.json.validate[RepositoryList]