将json结果传递给Play / Scala中的视图

时间:2015-03-26 18:00:14

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

模型 -

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],以便我可以将结果传递到视图中。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:0)

jsonResults的类型不会是" List [..]",因为match-statement并不总是返回你的情况下的列表:

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

通过相应地更改JsError-case,确保您的代码返回一个列表。还要确保json-validator返回一个列表。

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

答案 1 :(得分:0)

我能够通过使用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))
}