5

I started trying Scala and Play to parse through Json data, and was following the tutorial at https://www.playframework.com/documentation/2.3.9/ScalaJson. Now, when I try to run the sample code given there which is:

val json: JsValue = Json.parse("""{
  "name" : "Watership Down",
  "location" : {
    "lat" : 51.235685,
    "long" : -1.309197
  },
  "residents" : [ {
    "name" : "Fiver",
    "age" : 4,
    "role" : null
  }, {
    "name" : "Bigwig",
    "age" : 6,
    "role" : "Owsla"
  } ]
}
""")

val lat = json \ "location" \ "lat"

I get the following error:

java.lang.NoSuchMethodError: play.api.libs.json.JsValue.$bslash(Ljava/lang/String;)Lplay/api/libs/json/JsValue;

What am I doing wrong? I'm using Scala 2.10 and Play 2.3.9.

Thanks.

drunkenfist
  • 2,958
  • 12
  • 39
  • 73
  • `JsLookupResult` is new in 2.4. Are you sure you're using 2.1? – Ryan Jul 29 '15 at 04:32
  • 2.4 brought in significant changes to the JSON library. Read the 2.4 tutorial rather than the ancient 2.1 tutorial. – Ryan Jul 29 '15 at 05:19
  • Not sure why I was under the impression that I was using 2.1. Anyway, I had to update my version to 2.3.9. But I'm still facing some issues when I try to run the sample code. I have updated my question. – drunkenfist Jul 29 '15 at 07:29
  • Looks like my code was still referring to Play 2.4 for run time. Updating it to 2.3.9 resolved the problem. Thanks. – drunkenfist Jul 29 '15 at 21:48

1 Answers1

10

In Play 2.4.x, JsLookupResult represents the value at a particular Json path, either an actual Json node or undefined. JsLookupResult has two subclasses: JsDefined and JsUndefined respectively.

You can modify your code as the following:

val name: JsLookupResult = json \ "user" \ "name"

name match {
  case JsDefined(v) => println(s"name = ${v.toString}")
  case undefined: JsUndefined => println(undefined.validationError)
}
Luong Ba Linh
  • 802
  • 5
  • 20
  • Thanks, but it looks like I have to update my Play framework to 2.3.9. I'm still facing some issues. I have updated my question. – drunkenfist Jul 29 '15 at 07:30
  • https://github.com/luongbalinh/play-mongo This is a simple full-stack web application using Play 2.4.2 for endpoint backend, Reactivemongo for reactive MongoDB driver, Guice for dependency injection, Spec2 and Mockito for unit testing and integration testing, Frisby for endpoint testing, and AngularJs, Bookstrap and Coffee script for frontend. – Luong Ba Linh Jul 29 '15 at 09:17
  • What should I do with that? I cannot use Play 2.4.x. I need to use 2.3.x. – drunkenfist Jul 29 '15 at 17:07
  • Looks like my code was still referring to Play 2.4 for run time. Updating it to 2.3.9 resolved the problem. Thanks. – drunkenfist Jul 29 '15 at 21:49