Parsing JSON messages with JsonSlurper

The first thing you probably want to do with the JSON data is to parse it. JSON support was introduced in Groovy 1.8. The class for consuming JSON is named JsonSlurper and it behaves similarly to the XmlSlurper, presented in the Reading XML using XmlSlurper recipe in Chapter 5, Working with XML in Groovy.

This recipe introduces the reader to JsonSlurper and shows how to parse a JSON file and how to navigate the data structure created by JsonSlurper.

Getting ready

Let's assume we have a ui.json file which stores a definition of the UI layout for some JavaScript framework:

{
  "items":[
  {
    "type":"chart",
    "height":270,
    "width":319,
    "animate":true,
    "insetPadding":20,
    "axes":[
    {
      "type":"Time",
      "fields":[ "x" ],
      "position":"left",
      "title":"Time"
    },
    {
      "type":"Numeric",
      "fields":[ "y" ],
      "position":"bottom",
      "title":"Profit in EUR"
    }
    ],
    "series":[
    {
      "type":"bar",
      "label":{
        "display":"insideEnd",
        "field":"y",
        "color":"#333",
        "text-anchor":"middle"
     },
     "axis":"bottom",
     "xField":"x",
     "yField":[ "y" ]
    }
    ]
  }
  ]
}

How to do it...

The JSON data can be easily parsed with the help of the groovy.json.JsonSlurper class.

  1. The groovy.json package is not included in the list of packages imported by default. For this reason, you need to explicitly import JsonSlurper:
    import groovy.json.JsonSlurper
    def reader = new FileReader('ui.json')
    def ui = new JsonSlurper().parse(reader)

    The parse method of JsonSlurper accepts a File or a Reader object. It is also possible to pass a String to JsonSlurper by invoking the parseText method.

  2. After the JSON payload is successfully parsed, you can easily navigate through the resulting object using the familiar GPath-like expressions and closures:
    ui.items.each { println it.type }
    
    println ui.items[0]
      .axes
      .find {
        it.fields.contains('y')
      }.title
  3. The complete output of the script looks like:
    chart
    Profit in EUR
    

How it works...

The first line in step 2 iterates through all the elements in the items node, which is a top-level collection in our JSON object and it prints the value of the type attribute of each of those objects. Since we have only one object in that collection it only prints chart in return.

The second line uses a slightly more complex expression. The expression's goal is simply to find the title used by the y axis.

The expression selects the first element of the items collection and subsequently gets the axes collection. It then searches the axes collection for the first element of the nested fields collection having the y value. Finally, it returns the title of the found element.

Unlike XmlSlurper, which uses an intermediate set of classes to present the XML tree, JsonSlurper transforms a JSON message to a nested combination of Maps and Lists.

For example, to show the actual classes used behind the scenes, we can fire up the following code:

println ui.getClass()
println ui.items.getClass()

It will print out the following class names:

class java.util.HashMap
class java.util.ArrayList

Knowing that the structure created by JsonSlurper is backed by Groovy's Collections, you can easily leverage all the Collection extension methods (such as each, find, and collect) available in Groovy to build expressions that search and modify your JSON objects.

There's more...

JsonSlurper is rather well-suited for most parsing needs. On the other hand, there are plenty of libraries available in the Java/Groovy ecosystem, which offer similar functionality:

See also

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.164.75