简体   繁体   English

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

[英]Traversing multiple JSON arrays in Play/Scala

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

I can successfully traverse location with this - 我可以成功遍历位置-

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())
}

Based on the documentation, I should be able to do something like this - 根据文档,我应该能够执行以下操作-

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

but it results in the following error - 但它导致以下错误-

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

At this point I'm just trying to understand how to return values from "renting" only. 在这一点上,我只是试图了解如何仅从“租赁”中返回值。 Eventually, I would like to map that result to a case class. 最终,我想将结果映射到案例类。

If your eventual goal is to parse this into case classes, just define those case classes and let Play do the heavy lifting. 如果您最终的目标是将其解析为案例类,则只需定义这些案例类,然后让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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM