Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Andrey Adamovich - Groovy 2 Cookbook - 2013.pdf
Скачиваний:
44
Добавлен:
19.03.2016
Размер:
26.28 Mб
Скачать

6

Working with JSON in Groovy

In this chapter, we will cover:

ff

ff

ff

ff

ff

ff

ff

Parsing JSON messages with JsonSlurper Constructing JSON messages with JsonBuilder Modifying JSON messages

Validating JSON messages Converting JSON message to XML

Converting JSON message to Groovy Bean

Using JSON to configure your scripts

Introduction

JSON (JavaScript Object Notation) (http://www.json.org/) is a data interchange format, similar in scope to XML or CSV. It uses a very lightweight serialization form and works very well for exchanging data between a web client (a browser) and a remote server, but it is not limited to only that.

JSON is also a subset of the object literal notation of JavaScript. Being a subset of JavaScript implies that a JSON payload can be processed by the language natively. This is the main reason why JSON has become such a popular format for transferring serialized data between a remote API (often a RESTful API) and a JavaScript client.

www.it-ebooks.info

Working with JSON in Groovy

But JSON is also very lightweight—especially if we compare it to the very chatty XML, the dethroned king of serialization—making it a suitable candidate for a general purpose data processing format (if you can live with some of its limitations such as the lack of namespace or poor complex data types support).

This chapter's recipes introduce the reader to Groovy native support for reading and producing JSON. We also look at some more advanced recipes such as conversion from and to XML and Groovy Beans.

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"

198

www.it-ebooks.info

Chapter 6

}

],

"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

199

www.it-ebooks.info

Working with JSON in Groovy

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:

ff Google GSON: http://code.google.com/p/google-gson/ ff JSONLib: http://json-lib.sourceforge.net/

ff Jackson: http://jackson.codehaus.org/

ff JSON.simple: http://code.google.com/p/json-simple/

200

www.it-ebooks.info

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]