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