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: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.