【问题标题】:Java - returning JSON from servlet with Gson libraryJava - 从带有 Gson 库的 servlet 返回 JSON
【发布时间】: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


【解决方案1】:

不确定您是否可以接受,但是:

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

不确定您是否可以接受对象语法。

【讨论】:

  • 好的,谢谢。我以为有一些更简单的方法,但似乎只有它一个。
  • 我通常将包装类作为我正在使用的任何控制器/servlet 的内部类,因为通常它在此之外没有用处。
  • 我可以再问一个问题吗?我试图用 javascript 显示这个数组的元素,但它说,它们是未定义的,但循环工作正常!我在做什么: var json = eval("("+xmlhttp.responseText+")"); for(json.cmets 中的 var 注释){alert(comment.author);}
  • @Lomer:我不是 javascript 专家,您最好发布一个新问题。
【解决方案2】:

除了包装对象之外,您还可以使用简单的java.util.Map 与单个条目,可能代码更少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-26
    • 1970-01-01
    • 2012-03-27
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-04
    相关资源
    最近更新 更多