【问题标题】:Passing json result to view in Play/Scala传递 json 结果以在 Play/Scala 中查看
【发布时间】:2015-03-26 18:00:14
【问题描述】:

型号-

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

【问题讨论】:

  • 您应该检查jsonResults 的类型,以及它是否与您在视图中采用的类型相匹配。

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


【解决方案1】:

jsonResults 的类型不会是“List[..]”,因为在您的情况下匹配语句并不总是返回一个列表:

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

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

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

【讨论】:

  • 关于错误处理的要点。我稍微修改了建议的实现,以便我仍然可以返回错误消息。我知道我必须将 Location 转换为列表,但我很难理解如何做到这一点。此外,我实际上需要一个 Renting 列表,而不是 Location 列表,并且我无法更改 .validate[Location],因为它用于 json 遍历。
  • 您可以使用列表中的地图功能进行转换。更多信息:brunton-spall.co.uk/post/2011/12/02/…
【解决方案2】:

我可以通过使用 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))
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-11
    相关资源
    最近更新 更多