【问题标题】:Add Object Root to JSON将对象根添加到 JSON
【发布时间】:2015-05-16 01:59:57
【问题描述】:

我正在寻找一种在 grails (2.4.5) 中将对象根添加到我的 JSON 的方法。通常,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
        ]
      }
   }
}

【问题讨论】:

    标签: json grails marshalling


    【解决方案1】:

    我回答了here,它只是将根元素变成一个ma​​p,并用键gameslist添加到其中,然后进行转换到 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)      
    
       }
    
    }
    

    【讨论】:

    • 这不是我想要的,因为我不希望编组器从数据库中提取数据。此时数据已被提取。做两次是个坏主意。
    • @user903772 这只是展示如何将根元素添加到 JSON 中的示例。但是是的,使用分页可能是一个解决方案。
    • @Gregg,我不确定 list() 方法是使用休眠缓存还是直接命中数据库,但最好将此要求作为问题的一部分发布。
    【解决方案2】:

    这有帮助吗?

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2018-05-18
      • 1970-01-01
      • 2017-10-27
      • 2015-09-21
      • 2018-07-20
      • 2017-11-30
      相关资源
      最近更新 更多