Another Lift-JSON array example

As a quick little bit of code sharing, I gave my Sarah stocks plugin the ability to allow multiple spoken phrases for one command. For instance, a user can now say “check stock prices”, “get stock prices”, or “get stocks” to check their stocks. To do this, I added an array of phrases to the JSON file that describes the Stocks plugin.

Getting to the point of this post, the following Scala source code shows how to read an array of JSON string values using Lift-JSON:

package jsontests

import java.io._
import scala.collection.mutable._
import java.util.Properties
import net.liftweb.json.DefaultFormats
import net.liftweb.json._

object JsonTest extends App {

  val stocksJsonString = """
{
  "phrases" : [
      "check stock prices",
      "get stock prices",
      "get stocks"
  ],
  "stocks": [
  { "stock": {
    "symbol": "AAPL",
    "name": "Apple",
    "price": "0"
  }},
  { "stock": {
    "symbol": "GOOG",
    "name": "Google",
    "price": "0"
  }}
  ]
}
"""
   
  implicit val formats = DefaultFormats  // for json handling
  case class Stock(val symbol: String, val name: String, var price: String)
 
  def getStocks(stocksJsonString: String): Array[Stock] = {
    val stocks = ArrayBuffer[Stock]()
    val json = JsonParser.parse(stocksJsonString)

    // (1) used 'values' here because 'extract' was not working in Eclipse
    val phrases = (json \\ "phrases").children  // List[JString]
    println("\nphrases: " + phrases)
    for (p <- phrases) {                        // for each JString
      println("p.values = " + p.values)
    }

    // (2) this works okay with "sbt run"
    println("\nphrases: " + phrases)
    for (p <- phrases) {
      val x = p.extract[String]
      println("x = " + x)
    }

    // (3) access the stocks
    val elements = (json \\ "stock").children
    for ( acct <- elements ) {
      val stock = acct.extract[Stock]
      stocks += stock
    }
    stocks.toArray
  }
 
  getStocks(stocksJsonString).foreach(println)

}

I think the extract method is the preferred approach, but I had a problem getting it to work in Eclipse initially, so I also show the values approach. (I eventually got extract working in Eclipse ... I don’t remember what the problem was.)

In summary, if you need to extract a list/array of string values from JSON using Scala and Lift-JSON, I hope this example is helpful.