Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/flash/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
将json结果传递到Play/Scala中的视图_Json_Scala_Playframework_Playframework 2.0_Scala 2.10 - Fatal编程技术网

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

将json结果传递到Play/Scala中的视图,json,scala,playframework,playframework-2.0,scala-2.10,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 }

模型-

看法-

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
}

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

jsonResults的类型将不会是“List[…]”,因为match语句在您的情况下并不总是返回列表:

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))
}
通过相应地更改JsError案例,确保代码返回一个列表。还要确保json验证程序返回一个列表

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

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

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

您应该检查
jsonResults
的类型,以及该类型是否与您在视图中采用的类型相匹配。错误处理的要点很好。我稍微修改了建议的实现,以便仍然可以返回错误消息。我知道我必须将位置转换为列表,但我很难理解如何才能做到这一点。此外,我实际上需要一个租赁列表,而不是位置列表,我无法更改
.validate[Location]
,因为它用于json遍历。您可以使用列表上的map函数来转换它。更多信息:
(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))
}