Package groovy.json
Class JsonBuilder
java.lang.Object
groovy.lang.GroovyObjectSupport
groovy.json.JsonBuilder
- All Implemented Interfaces:
GroovyObject
,Writable
A builder for creating JSON payloads.
This builder supports the usual builder syntax made of nested method calls and closures, but also some specific aspects of JSON data structures, such as list of values, etc. Please make sure to have a look at the various methods provided by this builder to be able to learn about the various possibilities of usage.
Example:
def builder = new groovy.json.JsonBuilder()
def root = builder.people {
person {
firstName 'Guillame'
lastName 'Laforge'
// Named arguments are valid values for objects too
address(
city: 'Paris',
country: 'France',
zip: 12345,
)
married true
// a list of values
conferences 'JavaOne', 'Gr8conf'
}
}
// creates a data structure made of maps (Json object) and lists (Json array)
assert root instanceof Map
assert builder.toString() == '{"people":{"person":{"firstName":"Guillame","lastName":"Laforge","address":{"city":"Paris","country":"France","zip":12345},"married":true,"conferences":["JavaOne","Gr8conf"]}}}'
- Since:
- 1.8.0
-
Constructor Summary
ConstructorDescriptionInstantiates a JSON builder.JsonBuilder
(JsonGenerator generator) Instantiates a JSON builder with a configured generator.JsonBuilder
(Object content) Instantiates a JSON builder with some existing data structure.JsonBuilder
(Object content, JsonGenerator generator) Instantiates a JSON builder with some existing data structure and a configured generator. -
Method Summary
Modifier and TypeMethodDescriptionA closure passed to a JSON builder will create a root JSON objectA collection and closure passed to a JSON builder will create a root JSON array applying the closure to each object in the collectionVarargs elements as arguments to the JSON builder create a root JSON arraycall
(Collection coll, Closure c) Delegates tocall(Iterable, Closure)
A list of elements as arguments to the JSON builder creates a root JSON arrayNamed arguments can be passed to the JSON builder instance to create a root JSON objectinvokeMethod
(String name, Object args) A method call on the JSON builder instance will create a root object with only one key whose name is the name of the method being called.Pretty-prints and formats the JSON payload.toString()
Serializes the internal data structure built with the builder to a conformant JSON payload stringThe JSON builder implements theWritable
interface, so that you can have the builder serialize itself the JSON payload to a writer.Methods inherited from class groovy.lang.GroovyObjectSupport
getMetaClass, setMetaClass
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
Methods inherited from interface groovy.lang.GroovyObject
getProperty, setProperty
-
Constructor Details
-
JsonBuilder
public JsonBuilder()Instantiates a JSON builder. -
JsonBuilder
Instantiates a JSON builder with a configured generator.- Parameters:
generator
- used to generate the output- Since:
- 2.5.0
-
JsonBuilder
Instantiates a JSON builder with some existing data structure.- Parameters:
content
- a pre-existing data structure
-
JsonBuilder
Instantiates a JSON builder with some existing data structure and a configured generator.- Parameters:
content
- a pre-existing data structuregenerator
- used to generate the output- Since:
- 2.5.0
-
-
Method Details
-
getContent
-
call
Named arguments can be passed to the JSON builder instance to create a root JSON objectExample:
def json = new groovy.json.JsonBuilder() json name: "Guillaume", age: 33 assert json.toString() == '{"name":"Guillaume","age":33}'
- Parameters:
m
- a map of key / value pairs- Returns:
- a map of key / value pairs
-
call
A list of elements as arguments to the JSON builder creates a root JSON arrayExample:
def json = new groovy.json.JsonBuilder() def result = json([1, 2, 3]) assert result instanceof List assert json.toString() == "[1,2,3]"
- Parameters:
l
- a list of values- Returns:
- a list of values
-
call
Varargs elements as arguments to the JSON builder create a root JSON arrayExample:
def json = new groovy.json.JsonBuilder() def result = json 1, 2, 3 assert result instanceof List assert json.toString() == "[1,2,3]"
- Parameters:
args
- an array of values- Returns:
- a list of values
-
call
A collection and closure passed to a JSON builder will create a root JSON array applying the closure to each object in the collectionExample:
class Author { String name } def authors = [new Author (name: "Guillaume"), new Author (name: "Jochen"), new Author (name: "Paul")] def json = new groovy.json.JsonBuilder() json authors, { Author author
->
name author.name } assert json.toString() == '[{"name":"Guillaume"},{"name":"Jochen"},{"name":"Paul"}]'- Parameters:
coll
- a collectionc
- a closure used to convert the objects of coll- Returns:
- a list of values
-
call
Delegates tocall(Iterable, Closure)
-
call
A closure passed to a JSON builder will create a root JSON objectExample:
def json = new groovy.json.JsonBuilder() def result = json { name "Guillaume" age 33 } assert result instanceof Map assert json.toString() == '{"name":"Guillaume","age":33}'
- Parameters:
c
- a closure whose method call statements represent key / values of a JSON object- Returns:
- a map of key / value pairs
-
invokeMethod
A method call on the JSON builder instance will create a root object with only one key whose name is the name of the method being called. This method takes as arguments:- a closure
- a map (ie. named arguments)
- a map and a closure
- or no argument at all
Example with a classical builder-style:
Or alternatively with a method call taking named arguments:def json = new groovy.json.JsonBuilder() def result = json.person { name "Guillaume" age 33 } assert result instanceof Map assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
If you use named arguments and a closure as last argument, the key/value pairs of the map (as named arguments) and the key/value pairs represented in the closure will be merged together — the closure properties overriding the map key/values in case the same key is used.def json = new groovy.json.JsonBuilder() json.person name: "Guillaume", age: 33 assert json.toString() == '{"person":{"name":"Guillaume","age":33}}'
The empty args call will create a key whose value will be an empty JSON object:def json = new groovy.json.JsonBuilder() json.person(name: "Guillaume", age: 33) { town "Paris" } assert json.toString() == '{"person":{"name":"Guillaume","age":33,"town":"Paris"}}'
def json = new groovy.json.JsonBuilder() json.person() assert json.toString() == '{"person":{}}'
- Specified by:
invokeMethod
in interfaceGroovyObject
- Parameters:
name
- the single keyargs
- the value associated with the key- Returns:
- a map with a single key
-
toString
Serializes the internal data structure built with the builder to a conformant JSON payload stringExample:
def json = new groovy.json.JsonBuilder() json { temperature 37 } assert json.toString() == '{"temperature":37}'
-
toPrettyString
Pretty-prints and formats the JSON payload.This method calls the JsonLexer to parser the output of the builder, so this may not be an optimal method to call, and should be used mainly for debugging purpose for a human-readable output of the JSON content.
- Returns:
- a pretty printed JSON output
-
writeTo
The JSON builder implements theWritable
interface, so that you can have the builder serialize itself the JSON payload to a writer.Example:
def json = new groovy.json.JsonBuilder() json { temperature 37 } def out = new StringWriter() out
<<
json assert out.toString() == '{"temperature":37}'- Specified by:
writeTo
in interfaceWritable
- Parameters:
out
- a writer on which to serialize the JSON payload- Returns:
- the writer
- Throws:
IOException
- if an error occurred while outputting data to the writer
-