【问题标题】:Play Framework WS: Returning JSON data as IntPlay Framework WS:将 JSON 数据返回为 Int
【发布时间】:2013-08-01 11:35:02
【问题描述】:

我正在尝试来自this 站点的代码(稍作修改),但在将结果作为Int 返回时遇到了问题。

class NeoService(rootUrl: String) {
    def this() = this("http://default/neo/URL/location/db/data")


    val stdHeaders = Seq(
        ("Accept", "application/json"), 
        ("Content-Type", "application/json") 
    )

    def executeCypher(query: String, params: JsObject) : Future[Response] = {
        WS.url(rootUrl + "/cypher").withHeaders(stdHeaders:_*).post(Json.obj(
            "query" -> query,
            "params" -> params
        ))
    }

    def findNode(id: Int) : Future[Option[Int]] = {
        val cypher = """
          START n=node({id})
          RETURN id(n) as id
       """.stripMargin

        val params = Json.obj("id" -> id)

        for (r <- executeCyhper(cypher, params)) yield {
            val data = (r.json \ "data").as[JsArray]
            if (data.value.size == 0)
               None
            else
               Some(data.value(0).as[JsArray].value(0).as[Int])
        }
    }
}

如果我将有效的 id 传递给 findNode(),它会给我这个错误:

[JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsnumber,WrappedArray())))))]

Some(data.value(0).as[JsArray].value(0).as[Int]) 行,如果我传递一个不存在的 id,它会给我这个错误:

[JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsarray,WrappedArray())))))]

在线val data = (response.json \ "data").as[JsArray]

如果我像这样传递Int

... else 
        Some(10)...

它工作正常。我不知道发生了什么以及错误消息试图告诉我什么。

【问题讨论】:

    标签: json scala neo4j playframework-2.1


    【解决方案1】:

    此消息告诉您的是,您提供的 JSON 无法以您期望的类型进行解析。

    第一个是关于Some(data.value(0).as[JsArray].value(0).as[Int])。显然data.value(0).as[JsArray].value(0) 不是数字,因此不能转换为 Int。

    对于第二个,val data = (response.json \ "data").as[JsArray] 因为 id 不存在,显然你得到的 Json 没有键“数据”,或者该键的值不是数组(null?)。

    我建议你在解析之前记录下 r.json 的值。你会明白为什么它失败了。 您还应该避免使用 as 并改用 validate (http://www.playframework.com/documentation/2.1.2/ScalaJsonRequests)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多