A simple Scala JSON parser example using Lift-JSON

Scala JSON FAQ: How can I parse JSON text or a JSON document with Scala?

As I continue to plug away on my computer voice control application (SARAH), last night I started working with JSON, specifically the Lift-JSON library (part of the Lift Framework), which seems to be the preferred JSON library of the Scala community.

While most Scala JSON examples seem to jump right into the hard things, I thought I'd start by sharing a simple JSON example, where I create a multiline JSON string, then parse that string directly into a Scala object:

package tests

import net.liftweb.json._

object SarahEmailPluginConfigTest {

implicit val formats = DefaultFormats
case class Mailserver(url: String, username: String, password: String)

val json = parse(
"""
{ 
  "url": "imap.yahoo.com",
  "username": "myusername",
  "password": "mypassword"
}
"""
)

  def main(args: Array[String]) {
    val m = json.extract[Mailserver]
    println(m.url)
    println(m.username)
    println(m.password)
  }

}

If you know Scala and are familiar with JSON, there isn't much to say about this example. A few notes:

  • I define a Scala case class named Mailserver.
  • I define a String named json, which contains my JSON content.
  • I parse/extract that JSON string into an instance of my Mailserver class. 'm' is a Mailserver object.

Note: This simple JSON example is based on a more-complicated JSON example here at assembla.com.

The right Lift-JSON jar for Scala 2.9

If you're using Scala 2.9.x, one thing you might run into is that it's a little hard to find the right Lift-JSON jars at the moment. Here are some URLs I used to get the correct Lift-JSON jar:

Found this URL
http://scala-tools.org/repo-releases/net/liftweb/lift-json_2.9.0-1/2.4-M2/

after reading this web page:
http://groups.google.com/group/liftweb/browse_thread/thread/fbb4b43b518108a7?pli=1
 
This jar is probably better:
http://scala-tools.org/repo-releases/net/liftweb/lift-json-ext_2.9.1/2.4-RC1/

In summary, if you're just learning how to parse JSON with Scala, I hope this Lift-JSON example has been helpful.