1

I have the following code:

    def customers = Customer.findAll()
    def json = new JsonBuilder()
    json {
        customers.each { customer ->
            id customer.id
            name customer.name
            address customer.address
        }
    }

I'm expecting that the result is an json array of customers, but instead it only contains 1 customer. Note the customers list contains 2 elements.

I saw some other post mentioning to use something like:

customers.collect { 
    Customer c -> [id: c.id, name: c.name, address: c.address]
}   

But this style does not really fit nicely in the builder. E.g. I have to use colons : to assign values.

Is there another approach without creating groovy objects?

Marcel Overdijk
  • 11,041
  • 17
  • 71
  • 110

2 Answers2

0

No, json is a map, and you need a list of maps. What you are doing with each is re-assigning the id, name and address fields, so you just get the last value.

So you need to collect a list of maps together as you have in the question.

dmahapatro
  • 49,365
  • 7
  • 88
  • 117
tim_yates
  • 167,322
  • 27
  • 342
  • 338
0

What you need is just this.

def json = new JsonBuilder( customers )

if there are no additional item in customer that is not required in the json.

dmahapatro
  • 49,365
  • 7
  • 88
  • 117