将对象根添加到JSON [英] Add Object Root to JSON
本文介绍了将对象根添加到JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在寻找一种在grails(2.4.5)中将对象根添加到我的JSON的方法。通常情况下,Grails会呈现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"}]
但我需要它看起来像:
{"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
]
}
}
}
推荐答案
我回答了这里,它只是使根元素成为地图,然后使用游戏
添加列表,然后将其转化为 JSON 。
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)
}
}
这篇关于将对象根添加到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文