A Scala JSON array parsing example using Lift-JSON

I just worked through some Scala Lift-JSON issues, and thought I'd share some source code here.

In particular, I'm trying to parse a JSON document into Scala objects, and I'm using Lift-JSON to do so. One of the things I'm doing here is to parse some of the JSON text into an array of objects, in this case an array of String objects.

First, here's the Scala source code for my example, and then a description will follow:

package tests

import net.liftweb.json.DefaultFormats
import net.liftweb.json._

object SarahScalaLiftJsonTest {

  implicit val formats = DefaultFormats

  val mailAccountString ="""
  "accounts": [
  { "emailAccount": {
    "accountName": "YMail",
    "username": "USERNAME",
    "password": "PASSWORD",
    "url": "imap.yahoo.com",
    "minutesBetweenChecks": 1,
    "usersOfInterest": ["barney", "betty", "wilma"]
  { "emailAccount": {
    "accountName": "Gmail",
    "username": "USER",
    "password": "PASS",
    "url": "imap.gmail.com",
    "minutesBetweenChecks": 1,
    "usersOfInterest": ["pebbles", "bam-bam"]
  def main(args: Array[String]) {
    val json = parse(mailAccountString)
    val elements = (json \\ "emailAccount").children
    for ( acct <- elements ) {
      val m = acct.extract[EmailAccount]

 * A case class to match the json properties.
case class EmailAccount(
  accountName: String,
  url: String, 
  username: String, 
  password: String,
  minutesBetweenChecks: Int,
  usersOfInterest: List[String]

As you can see:

  • My JSON text is stored in the Scala variable named mailAccountString.
  • I parse this into a variable named json using the parse function from the Lift-JSON library.
  • I search for all elements named emailAccount.
  • Within the for loop I extract each element as an EmailAccount object. (That's handled in the extract function.)
  • After that, I just print the information.
  • All I had to do in my Scala code to make this work was define the EmailAccount class as a "case class".

I don't have anything else to add at this time, so I'll leave it at that. In summary, if you need a Scala JSON parsing example using the Lift-JSON library, I hope this example source code has been helpful.