在 Play/Scala 中遍历多个 JSON 数组

Traversing multiple JSON arrays in Play/Scala

{
    "location":{
        "residents":[{
            "renting":[{
                "name":"John Doe"
                "pets":"2"
            },{
                "name":"Jane Smith"
                "pets":"2"
            }]
        }]
    }
}

我可以通过这个成功遍历位置 -

val json = ...

val rentReads = (__ \ 'location).read[String]

val rentResult = json.validate[String](rentReads)

rentResult match {
  case s: JsSuccess[String] => Ok(s.get)
  case e: JsError => Ok("Errors: " + JsError.toFlatJson(e).toString())
}

根据文档,我应该可以做这样的事情 -

val skillReads = ((__ \ 'location) \ 'residents)(0).read[String]

但它会导致以下错误 -

Errors: {"obj.VariationResultsWrapper.VariationResultSets[0]":[{"msg":"error.path.missing","args":[]}]}

在这一点上,我只是想了解如何仅从 "renting" 中获取 return 值。最终,我想将该结果映射到一个案例 class.

如果您的最终目标是将其解析为案例 类,只需定义这些案例 类 并让 Play 完成繁重的工作。

case class Renting(name: String, pets: String)
case class Resident(renting: List[Renting])
case class Location(residents: List[Resident])

implicit val rentingFormat = Json.format[Renting]
implicit val residentFormat = Json.format[Resident]
implicit val locationFormat = Json.format[Location]

(json \ "location").validate[Location]
res1: play.api.libs.json.JsResult[Location] = JsSuccess(Location(List(Resident(List(Renting(John Doe,2), Renting(Jane Smith,2))))),/residents)