Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a Json String in Scala using Play framework

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.

like image 374
drunkenfist Avatar asked Jul 29 '15 03:07

drunkenfist


People also ask

What is JSON parse () method?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

What is the best JSON library for Scala?

Argonaut is a great library. It's by far the best JSON library for Scala, and the best JSON library on the JVM. If you're doing anything with JSON in Scala, you should be using Argonaut. circe is a fork of Argonaut with a few important differences.


1 Answers

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)
}
like image 144
Luong Ba Linh Avatar answered Oct 10 '22 08:10

Luong Ba Linh