I need to build a simple JSON array in JSON but in the loop it overwrites the first value during every iteration.
def jsonBuilder = new groovy.json.JsonBuilder()
contact.each {
jsonBuilder.contact(
FirstName: it.getFirstName(),
LastName: it.getLastName(),
Title: it.getTitle(),
)
}
It returns just the simple JSON and overwrites the value of every iteration and retains just the last one. What is the syntax for constructing a JSON Array in groovy?
No directly answers the question (it was about JsonBuilder) but if the goal is to get a JSON output a string it may be done in the following way (part of code borrowed from @dmahapatro answer), using JsonOutput:
Trick is to
collect
from the list of contacts. Assuming structure ofcontract
list is as below, follow the wayjsonBuilder
is used below.If you are looking for a JSONArray instead of a JSONObject as a final stucture, then use:
It does not make sense but if structure needed like below
then use
Using JsonBuilder doesn't work real well with
.each
; I've usedcollect
for this kind of thing. Below is an example of that should work for your case:The result for this is: