[英]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":[]}]}
在這一點上,我只是試圖了解如何僅從“租賃”中返回值。 最終,我想將結果映射到案例類。
如果您最終的目標是將其解析為案例類,則只需定義這些案例類,然后讓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.