0

I want something like this in my application with json builder

new JsonBuilder() {
            persons.collect{
                [
                        name: it.name,
                        age:  it.age,
                        companies: [{
                                        company1: it.company //The company comes from person object.
                                    },
                                    {
                                        company2: it.company
                                    }
                        ]
                ]
            }
        }

Here while accessing the company null pointer exception is being thrown as it is not considering the person iterator.Is there any other way to do it in this way??

Akshay
  • 1,161
  • 1
  • 12
  • 33
xxx
  • 11
  • 4

1 Answers1

0

you can define the name of iterator (closure default parameter name - it)

new JsonBuilder() {
    persons.collect{person->
        [
            name: person.name,
            age:  person.age,
            companies: [
                {
                    company1: person.company //The company comes from person object.
                },
                {
                    company2: person.company
                }
            ]
        ]
    }
}
daggett
  • 26,404
  • 3
  • 40
  • 56