15.3. Creating 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 ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.