【问题标题】:Traversing multiple JSON arrays in Play/Scala在 Play/Scala 中遍历多个 JSON 数组
【发布时间】:2015-03-15 07:17:01
【问题描述】:
{
    "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":[]}]}

此时我只是想了解如何仅从“出租”中返回值。最后,我想将该结果映射到一个案例类。

【问题讨论】:

    标签: json scala playframework playframework-2.0 scala-2.10


    【解决方案1】:

    如果您的最终目标是将其解析为案例类,只需定义这些案例类并让 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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-23
      • 2021-01-10
      • 1970-01-01
      • 2013-04-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 1970-01-01
      相关资源
      最近更新 更多