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

Chapter 6

See also

ff Constructing JSON messages with JsonBuilder

ff The Reading XML using XmlSlurper recipe in Chapter 5, Working with XML in Groovy

ff http://www.json.org/

ff http://groovy.codehaus.org/gapi/groovy/json/JsonSlurper.html

Constructing JSON messages with JsonBuilder

This recipe provides an overview of another class introduced in Groovy 1.8, which helps to construct JSON messages, the JsonBuilder.

This class works like any other builder class in Groovy (see the Defining data structures as code in Groovy recipe from Chapter 3, Using Groovy Language Features). A data structure based on Lists and Maps is defined, and JSON is split out when the string representation is requested.

How to do it...

The following steps will show some examples of using JsonBuilder.

1.Let's start right away with a simple script that builds the representation of a fictional customer:

import groovy.json.JsonBuilder

def builder = new JsonBuilder() builder.customer {

name 'John' lastName 'Appleseed' address {

streetName 'Gordon street' city 'Philadelphia' houseNumber 20

}

}

println builder.toPrettyString()

201

www.it-ebooks.info

Working with JSON in Groovy

2.The output of the previous script yields:

{

"customer": { "name": "John",

"lastName": "Appleseed", "address": {

"streetName": "Gordon street", "city": "Philadelphia", "houseNumber": 20

}

}

}

3.Here is a slightly more complex example of JsonBuilder usage, used to build the definition of a chart widget:

def chart = [ items: [

type: 'chart', height: 200, width: 300, axes: [

{

type 'Time' fields ([ 'x' ]) position 'left' title 'Time'

},

{

type 'Numeric' fields ( [ 'y' ] ) position 'bottom' title 'Profit in EUR'

}

]

]

]

def builder = new JsonBuilder(chart) println builder.toPrettyString()

The output of the previous statement is:

{

"items": [

{

202

www.it-ebooks.info

Chapter 6

"type": "chart", "height": 200, "width": 300, "axes": [

{

"type": "Time", "fields": [ "x" ], "position": "left", "title": "Time"

},

{

"type": "Numeric", "fields": [ "y" ], "position": "bottom", "title": "Profit in EUR"

}

]

}

]

}

How it works...

JsonBuilder can produce JSON-formatted output from Maps, Lists, and Java Beans (see the Converting JSON message to Groovy Bean recipe). The output is stored in memory, and it can be written to a stream or processed further. If we want to directly stream (instead of storing

it in memory) the data as it's created, we can use StreamingJsonBuilder instead of the

JsonBuilder.

In the example at step 1, we create an instance of the JsonBuilder class and we simply define the key/value pairs that contain the data structure we wish to create. The approach is very similar to any other builder, such as MarkupBuilder (see the Constructing XML content recipe in Chapter 5, Working with XML in Groovy).

In the second example, the builder is directly created by passing a variable containing a Map. The Map's keys are Strings as defined by the JSON standard, but the assigned values can be one of the following types:

ff One of the simple data type (for example, Boolean and String) permitted by JSON ff Another Map

ff Collection of the above

ff A closure or a collection of closures

203

www.it-ebooks.info

Working with JSON in Groovy

To demonstrate the flexibility of JsonBuilder in our example, we used different types, including closures.

See also

ff Parsing JSON messages with JsonSlurper

ff The Constructing XML content recipe in Chapter 5, Working with XML in Groovy

ff http://groovy.codehaus.org/gapi/groovy/json/JsonBuilder.html

Modifying JSON messages

After we've got acquainted with a way to read existing JSON messages (see the Parsing JSON messages with JsonSlurper recipe) and create our own (see Constructing JSON messages with JsonBuilder recipe), we need to have the ability to modify the messages that flow through our system.

This recipe will show how straightforward it is to alter the content of a JSON document in Groovy.

How to do it...

Let's use the same JSON data located in the ui.json file that we used in the Parsing JSON messages with JsonSlurper recipe.

1.First of all we need to load and parse the JSON file: import groovy.json.*

def reader = new FileReader('ui.json') def ui = new JsonSlurper().parse(reader)

Since the data is actually just a nested structure, which consists of Maps, Lists and primitive data types, we can use the same API we would use for collections to navigate and change JSON data.

2.Consider the following snippet of code, which changes and removes some bits of the original JSON message:

ui.items[0].type = 'panel' ui.items[0].title = 'Main Window' ui.items[0].remove('axes') ui.items[0].remove('series')

204

www.it-ebooks.info

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