传递 json 结果以在 Play/Scala 中查看

Passing json result to view in Play/Scala

型号-

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

查看-

@(jsonResults: List[Renting])

@jsonResults.map { json =>
  Name: @json.name
  Pets: @json.pets
}

控制器-

val json: JsValue = Json.obj(
  "location" -> Json.obj(
    "residents" -> Json.arr(
      Json.obj(
        "renting" -> Json.arr(
          Json.obj(
            "name" -> "John Doe",
            "pets" -> 2
          ),
          Json.obj(
            "name" -> "Jane Smith",
            "pets" -> 1
          )
        )
      )
    )
  )
)

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

(json \ "location").validate[Location] match {
  case s: JsSuccess[Location] => {
    val location: Location = s.get
    /* Something happens here that converts Location to List[Renting] */
    Ok(views.html.index(location))
  }
  case e: JsError => Ok(JsError.toFlatJson(e))
}

根据 s.get.toString 的输出,似乎 json 被正确遍历;但是,我需要将类型从 Location 更改为 List[Renting] 以便我可以将结果传递到视图中。任何帮助将不胜感激!

json结果的类型不会是 "List[..]",因为匹配语句并不总是 return 在您的情况下是一个列表:

val jsonResults = (json \ "location").validate[Location] match {
  case s: JsSuccess[Location] => s.get
  case e: JsError => JsError.toFlatJson(e)
}

通过相应地更改 JsError-case 确保您的代码 return 是一个列表。还要确保 json-验证器 return 是一个列表。

val jsonResults = (json \ "location").validate[Location] match {
  case s: JsSuccess[Location] => s.get
  case e: JsError => Nil
}

我能够通过使用 head 从列表中获取第一个值来解决这个问题。见下文-

(json \ "location").validate[Location] match {
  case s: JsSuccess[Location] =>
    val renters = s.get.residents.head.renting
    Ok(views.html.index(renters))
  case e: JsError => Ok(JsError.toFlatJson(e))
}