4

我正在尝试这个站点的代码(稍作修改),我遇到了一个问题,将结果返回为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)...

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

4

1 回答 1

5

此消息告诉您的是,您提供的 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 )。

于 2013-08-01T12:13:03.520 回答