【发布时间】:2011-10-24 05:18:43
【问题描述】:
我正在使用 GSON 库。 我有一个返回 JSON 的程序。 JSON 以这种方式构造和返回:
Gson gson = new Gson();
//findNewComments returns List<Comment> comments
return gson.toJson(service.findNewComments(id,lastId));
所以结果是:
[
{
"id": 43,
"entryId": 19,
"author": " m8w46",
"body": "mw86",
"date": "WED 9, 2011"
},
{
"id": 44,
"entryId": 19,
"author": " n7w4",
"body": "nw77w4",
"date": "WED 9, 2011"
}
]
但是这个数组必须命名为“cmets”!
"comments": [
{
"id": 43,
"entryId": 19,
"author": " m8w46",
"body": "mw86",
"date": "WED 9, 2011"
},
{
"id": 44,
"entryId": 19,
"author": " n7w4",
"body": "nw77w4",
"date": "WED 9, 2011"
}
]
我该怎么做?
【问题讨论】:
-
可以是一个只有一个元素的对象吗,{"cmets":[...]}?
-
return "\"cmets\":" + gson.toJson(service.findNewComments(id,lastId)); ???
-
为什么一定要有这样的包装器?那里没有添加任何真实信息,为什么不按原样返回 JSON 数组?
-
我只在客户端代码需要特定格式时才这样做。
标签: java json servlets return gson