We can generate an object-type json by groovy's json builder:
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'
}
}
def jsonStr = builder.toString()
I like this type of syntax, but how to build an array-type json?
E.g.
[
{"code": "111", "value":"222"},
{"code": "222", "value":"444"}
]
I found some documents which say we should use JsonBuilder()
constructor:
def mydata = [ ["code": "111", "value":"222"],["code": "222", "value":"444"] ]
def builder = new groovy.json.JsonBuilder(mydata)
def jsonStr = builder.toString()
But I preferred the first syntax. Is it able to use it generate array-type json?
A JSON array contains zero, one, or more ordered elements, separated by a comma. The JSON array is surrounded by square brackets [ ] . A JSON array is zero terminated, the first index of the array is zero (0). Therefore, the last index of the array is length - 1.
JsonSlurper is a class that parses JSON text or reader content into Groovy data structures (objects) such as maps, lists and primitive types like Integer , Double , Boolean and String . The class comes with a bunch of overloaded parse methods plus some special methods such as parseText , parseFile and others.
public interface JsonObjectBuilder. A builder for creating JsonObject models from scratch. This interface initializes an empty JSON object model and provides methods to add name/value pairs to the object model and to return the resulting object.
The syntax you propose doesn't look possible, as I don't believe it's valid groovy. A closure such as {"blah":"foo"}
doesn't makes sense to groovy, and you're going to be constrained by syntactical limitations. I think the best you're going to be able to do is something within the following:
def root = builder.call (
[
{
code "111"
value "222"
},
{code "222"; value "444"}, //note these are statements within a closure, so ';' separates instead of ',', and no ':' used
[code: "333", value:"555"], //map also allowed
[1,5,7] //as are nested lists
]
)
it is also possible to create list of closures and pass it to builder
import groovy.json.*
dataList = [
[a:3, b:4],
[a:43, b:3, c:32]
]
builder = new JsonBuilder()
builder {
items dataList.collect {data ->
return {
my_new_key ''
data.each {key, value ->
"$key" value
}
}
}
}
println builder.toPrettyString()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With