What is the most straightforward way to parse JSON in Scala?

JAL picture JAL · Nov 12, 2010 · Viewed 8.3k times · Source

I'm working on a simple web application with Scala. The plan is to obtain JSON data from an external API, and insert it into a template (unfortunately, obtaining the data in XML is not an option).

I've tried working with Twitter's scala-json library, but I can't get it to compile properly (the code on github fails to update in sbt, saying standard-project 7.10 is not available and I haven't worked that out yet).

lift-json looks impressive, but appears to be a lot more elaborate than I need right now.

Trying to import a library I've worked with in Java, jsonic, results in various arcane errors. This is too bad because I rather like how straightforward jsonic is.

I've made a bit of progress with the built in scala.util.parsing.json.JSON, but actually I can't tell how to access the elements. I'm somewhat new to Scala, as you may have noted. How do you access the properties of JSONObjects?

scala.util.parsing.json.JSON has a lot of information, but is there a straightforward tutorial on how to use this anywhere?

I'm really only interested in deserializing JSON at the moment, to Ints, Strings, Maps and Lists. I don't have a need to serialize objects or make the deserialized objects fit into a class at the moment.

Can anyone point me to ways to work with one of the aforementioned libraries, or help me get set up with a Java lib that will do what I want?

Answer

Joni picture Joni · Nov 12, 2010

Lift JSON provides several different styles of deserializing JSON. Each have their pros and cons.

val json = JsonParser.parse(""" { "foo": { "bar": 10 }} """)

LINQ style query comprehension:

scala> for { JField("bar", JInt(x)) <- json } yield x 

res0: List[BigInt] = List(10)

More examples: http://github.com/lift/lift/blob/master/framework/lift-base/lift-json/src/test/scala/net/liftweb/json/QueryExamples.scala

Extract values with case classes

implicit val formats = net.liftweb.json.DefaultFormats 
case class Foo(foo: Bar) 
case class Bar(bar: Int) 
json.extract[Foo] 

More examples: https://github.com/lift/lift/blob/master/framework/lift-base/lift-json/src/test/scala/net/liftweb/json/ExtractionExamples.scala

XPath style

scala> val JInt(x) = json \ "foo" \ "bar"

x: BigInt = 10

Non-type safe values

scala> json.values

res0: Map((foo,Map(bar -> 10)))