Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use jsonbuilder with collections?

Tags:

groovy

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?

like image 732
Sean Nguyen Avatar asked Mar 29 '12 16:03

Sean Nguyen


1 Answers

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()
like image 160
epidemian Avatar answered Oct 05 '22 06:10

epidemian