Groovy Simple JSON array builder

user2093576 picture user2093576 · Jan 29, 2015 · Viewed 24.7k times · Source

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?

Answer

dmahapatro picture dmahapatro · Jan 29, 2015

Trick is to collect from the list of contacts. Assuming structure of contract list is as below, follow the way jsonBuilder is used below.

def contact = [ 
    [ getFirstName : { 'A' }, getLastName : { 'B' }, getTitle : { 'C' } ], 
    [ getFirstName : { 'D' }, getLastName : { 'E' }, getTitle : { 'F' } ], 
    [ getFirstName : { 'G' }, getLastName : { 'H' }, getTitle : { 'I' } ]     
]

def jsonBuilder = new groovy.json.JsonBuilder()

jsonBuilder {
    contacts contact.collect { 
        [ 
            FirstName: it.getFirstName(), 
            LastName: it.getLastName(), 
            Title: it.getTitle() 
        ] 
    }
}

println jsonBuilder.toPrettyString()


// Prints
{
    "contacts": [
        {
            "FirstName": "A",
            "LastName": "B",
            "Title": "C"
        },
        {
            "FirstName": "D",
            "LastName": "E",
            "Title": "F"
        },
        {
            "FirstName": "G",
            "LastName": "H",
            "Title": "I"
        }
    ]
}

If you are looking for a JSONArray instead of a JSONObject as a final stucture, then use:

jsonBuilder(
    contact.collect { 
        [ 
            FirstName: it.getFirstName(), 
            LastName: it.getLastName(), 
            Title: it.getTitle() 
        ]
    }
)

// OP
[
    {
        "FirstName": "A",
        "LastName": "B",
        "Title": "C"
    },
    {
        "FirstName": "D",
        "LastName": "E",
        "Title": "F"
    },
    {
        "FirstName": "G",
        "LastName": "H",
        "Title": "I"
    }
]

It does not make sense but if structure needed like below

[
    {
        "contact": {
            "FirstName": "A",
            "LastName": "B",
            "Title": "C"
        }
    },
    {
        "contact": {
            "FirstName": "D",
            "LastName": "E",
            "Title": "F"
        }
    },
    {
        "contact": {
            "FirstName": "G",
            "LastName": "H",
            "Title": "I"
        }
    }
]

then use

jsonBuilder(
    contact.collect { 
        [ 
            contact : [ 
                FirstName: it.getFirstName(), 
                LastName: it.getLastName(), 
                Title: it.getTitle() 
            ] 
        ]
    }
)