我正在使用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"
    }
]


但是此数组必须命名为“ comments”!

"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"
    }
]


我怎样才能做到这一点?

最佳答案

不知道这是否可以接受,但是:

public class CommentWrapper {
    List<Comments> comments;
    public CommentWrapper(List<Comment> comments) {
       this.comments = comments;
    }
}


然后,您可以执行以下操作:

return new Gson().toJson(new CommentWrapper(service.findNewComments(id,lastId)));


结果是:

{
    "comments": [
        ....your data here...
    ]
}


不知道对象语法是否可以接受。

09-10 00:59
查看更多