开发者

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

开发者 https://www.devze.com 2022-12-25 03:48 出处:网络
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.

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消