I need to create a json message like this:
{
success:true,
count:3,
data: [
{id:1},
{id:2},
{id:3}
]
}
I have tried this
import groovy.json.*
def tasks = [1, 2,3]
def json = new JsonBuilder()
json{
success(true)
count(tasks.size())
data {
tasks.each {
data(
id: it
)
}
}
}
JsonOutput.prettyPrint(json.toString())
but it doesn't work. Can somebody show me how to make it work?
I'd recommend transforming the tasks list into a list of the form [[id: 1], [id: 2], [id: 3]]
and then "jsonizing" it:
import groovy.json.JsonBuilder
def tasks = [1, 2, 3]
def json = new JsonBuilder()
json{
success(true)
count(tasks.size())
data(tasks.collect {[id: it]})
}
println json.toPrettyString()
I usually prefer generating the data structures in Groovy first (e.g. lists, maps) and then convert them to JSON, that way I usually have more control over the data that is going to be serialized and I don't need to include logic on the serialization code.
import groovy.json.JsonBuilder
def tasks = [1, 2, 3]
def data = [
success: true,
count: tasks.size(),
data: tasks.collect {[id: it]}
]
def json = new JsonBuilder(data)
println json.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