将对象根添加到JSON

时间:2015-05-16 01:59:58

标签: json grails marshalling

我正在寻找一种方法来将对象根添加到grails中的JSON(2.4.5)。通常,Grails会像这样呈现JSON对象列表:

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

但我需要它看起来像:

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

理想情况下,我想调整我创建的自定义编组器来执行此操作,但我不确定如何解决此问题:

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

2 个答案:

答案 0 :(得分:1)

我回答了here,它只是将根元素设为地图,并使用键games列表添加到其中,然后将其转换为 JSON

所以这适合你的情况:

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)      

   }

}

答案 1 :(得分:0)

这有帮助吗?

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
相关问题