How to create a simple Scala object from a JSON String

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is a short recipe, Recipe 15.3, “How to create a simple Scala object from a JSON String.”

Problem

You need to convert a JSON string into a simple Scala object, such as a Scala case class that has no collections.

Solution

Use the Lift-JSON library to convert a JSON string to an instance of a case class. This is referred to as deserializing the string into an object.

The following code shows a complete example of how to use Lift-JSON to convert a JSON string into a case class named MailServer. As its name implies, MailServer represents the information an email client needs to connect to a server:

import net.liftweb.json._

// a case class to represent a mail server
case class MailServer(url: String, username: String, password: String)

object JsonParsingExample extends App {
    implicit val formats = DefaultFormats
    // simulate a json string
    val jsonString = """
  {
  "url": "imap.yahoo.com",
  "username": "myusername",
  "password": "mypassword"
  }
  """

  // convert a String to a JValue object
  val jValue = parse(jsonString)

  // create a MailServer object from the string
  val mailServer = jValue.extract[MailServer]
  println(mailServer.url)
  println(mailServer.username)
  println(mailServer.password)
}

In this example, the jsonString contains the text you’d expect to receive if you called a web service asking for a MailServer instance. That string is converted into a Lift-JSON JValue object with the parse function:

val jValue = parse(jsonString)

Once you have a JValue object, use its extract method to create a MailServer object:

val mailServer = jValue.extract[MailServer]

The JValue class is the root class in the Lift-JSON abstract syntax tree (AST), and its extract method builds a case class instance from a JSON string.

Working with objects that have collections is a little more difficult, and that process is covered in the next recipe.

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

You can find the Scala Cookbook at these locations:

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.