Play Framework WS: Returning JSON data as Int

json, neo4j, playframework-2.1, scala

Solution

What this message is telling you is that the JSON your providing is not parseable in the type you expect.

The first one is about `Some(data.value(0).as[JsArray].value(0).as[Int])`. apparently `data.value(0).as[JsArray].value(0)` is not a Number, and therefore can't be converted to an Int.

For the second one, `val data = (response.json \ "data").as[JsArray]` since the id does not exist, apparently the Json you get has no key 'data', or the value at that key is not an array (null ?).

I suggest you log the value of r.json before parsing. You'll see exactly why it's failing. You should also avoid using `as` and use validate instead (http://www.playframework.com/documentation/2.1.2/ScalaJsonRequests).

Problem

i was trying out the code from this site (with a little modification) and i ran into a problem returning the result as an `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]) } } } ``` if i pass a valid id into `findNode()` it gives me this error: `[JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsnumber,WrappedArray())))))]` at the line `Some(data.value(0).as[JsArray].value(0).as[Int])` and if i pass an id that does not exist, it gives me this error: `[JsResultException: JsResultException(errors:List((,List(ValidationError(validate.error.expected.jsarray,WrappedArray())))))]` at the line `val data = (response.json \ "data").as[JsArray]` if i just pass an `Int` like this: ``` ... else Some(10)... ``` it works fine. i have no idea what's going on and the what the error message is trying to tell me.

Original source