tags:

views:

185

answers:

1

Hello, 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.

+2  A: 

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

Dave
thanks you for your help.. I infact found the same post about the ObjectMarshaller, and worked great. I was still curious about the above solution. thanks a lot. Best Regards.
bsreekanth