Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rendering JSON in GRAILS with part of the attributes of an object

Tags:

json

grails

I am trying to build JSON from two fields. Say, I have a list of object(party), and I only need to pass 2 items as JSON pair.

def list = getMyList() //it contains 2 party objects
partyTo = array {
    for (i in list) {
        x partyId: i.id
        y partyName: i.toString()          
    }
}

The JSON string is

{
    "partyTo": [
        {"partyId":12},
        {"partyName":"Ar"},
        {"partyId":9},
        {"partyName":"Sr"}
    ]
}

when I extract it at the client, it is treated as 4 objects. I wanted as 2 objects, with the below format.

{
    "partyTo": [
        {"partyId":12, "partyName":"Ar"},
        {"partyId":9 , "partyName":"Sr"}
    ]
}

I'm getting 4 objects, probably because I use an array to build JSON. I'm new to groovy and JSON, so not sure about the right syntax combinations. Any help highly appreciated. thanks.

like image 966
bsr Avatar asked Apr 01 '10 18:04

bsr


1 Answers

You're right in that the problem is with the construction of your array. To get the required output you need an array of maps, one map for each object, and to get the overall "partyTo" object you need to add that list to another map:

    def parties = [
            ["id":12 , "name":"Ar", "privateField": "a"],
            ["id":9 , "name":"Sr", "privateField": "b"]
    ]

    def toRender = parties.collect { party->
        ["partyId": party.id, "partyName":party.name]
    }

    def result = ["partyTo" : toRender]
    render result as JSON

In other words, a Grails map turns into a JSON object and Grails arrays and lists become arrays in JSON

If you always want to render your "party" objects like this you might consider using an ObjectMarshaller. More details in this post on rendering JSON using object marshallers

like image 55
Dave Bower Avatar answered Oct 27 '22 01:10

Dave Bower