-->

Groovy Simple JSON array builder

2020-02-13 12:58发布

问题:

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?

回答1:

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() 
            ] 
        ]
    }
)


回答2:

Using JsonBuilder doesn't work real well with .each; I've used collect for this kind of thing. Below is an example of that should work for your case:

static class Contact {
    String firstName
    String lastName
    String title
}

Contact c1 = new Contact(firstName: "Tom", "lastName": "Potter", title: "Mr")
Contact c2 = new Contact(firstName: "Ryan", "lastName": "Olson", title: "Mr")

List<Contact> contactList = [c1,c2]
def jsonBuilder = new groovy.json.JsonBuilder()

jsonBuilder {
   contacts(contacts.collect{[firstName: it.firstName, lastName: it.lastName, title: it.title]})
}
println jsonBuilder.toPrettyString()

The result for this is:

{
    "contacts": [
        {
            "firstName": "Tom"
        },
        {
            "firstName": "Ryan"
        }
    ]
}


回答3:

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:

import groovy.json.JsonOutput

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

def list = ['contacts': contacts.collect { [FirstName: it.getFirstName(), LastName: it.getLastName(), Title: it.getTitle()] } ]

print JsonOutput.prettyPrint(JsonOutput.toJson(list))