Gregg
Gregg

Reputation: 35864

Add Object Root to JSON

I'm looking for a way to add object roots to my JSON in grails (2.4.5). Generally, Grails renders JSON list of objects like so:

[{"id":1,"title":"Catan","description":"Catan"}]

But I need it to look like:

{"games": [{"id":1,"title":"Catan","description":"Catan"}]}

Ideally I'd like to adjust the custom marshaller I've created to do this, but I'm not sure how to go about it:

class GameMarshaller {
    void register() {
      JSON.registerObjectMarshaller(Game) { Game node ->
        return [
          id            : node.id,
          title         : node.title,
          description : node.description
        ]
      }
   }
}

Upvotes: 0

Views: 191

Answers (2)

user903772
user903772

Reputation: 1562

Can this help?

def o = new JSONObject()
def arr = new JSONArray()
def g = new JSONObject()

games.each{
    g.put("id",it.id)
    ...
    arr.add(g)
}
o.put("games",arr)
respond o

Upvotes: 0

dsharew
dsharew

Reputation: 10665

I answered it here, it just about making the root element to be a map and adding the list into it with key games, then conver it to a JSON.


So this should work for your case:

class GameMarshaller {

    void register() {

      def games = Game.list().collect{ node ->
         [
          id            : node.id,
          title         : node.title,
          description : node.description
        ]
          }

      def result = ([games: games] as JSON)      

   }

}

Upvotes: 1

Related Questions