0

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
        ]
      }
   }
}
Gregg
  • 34,973
  • 19
  • 109
  • 214

2 Answers2

1

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)      

   }

}
Community
  • 1
  • 1
dsharew
  • 10,377
  • 6
  • 49
  • 75
  • That's not what I want, because I do NOT want the marshaller pulling the data from the database. The data will have already been fetched at this point. Doing it twice is a bad idea. – Gregg May 16 '15 at 16:00
  • @user903772 this is just an example to show how to add root element into a JSON. But yes using pagination could be a solution. – dsharew May 16 '15 at 16:23
  • @Gregg, I am not sure if list() method uses hibernate cache or directly hits database, but it is better if you post this requirement as part of your question. – dsharew May 16 '15 at 16:24
0

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
user903772
  • 1,554
  • 5
  • 32
  • 55