我有以下POJO:
public class Widget {
private String fizz;
private String buzz;
private String foo;
// Getters and setters for all 3...
}
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我试图List<List<Widget>>使用Java JSON库将a转换为JSON (但是我也接受使用GSON的任何答案).
这是我的代码:
// Returns a single List<Widget> with 2 Widgets in it...
List<List<Widget>> widgetGroups = getWidgetGroups();
String widgetGroupsAsJson = JSON.encode(widgetGroups);
System.out.println(widgetGroupsAsJson);
Run Code Online (Sandbox Code Playgroud)
这打印:
[
[
{
"fizz": "Yes",
"buzz": "Never",
"foo": "Always"
},
{
"fizz": "Sometimes",
"buzz": "Always",
"foo": "Pending"
}
]
]
Run Code Online (Sandbox Code Playgroud)
而我希望JSON显示为:
"widgetGroups": [
"widgetGroup": [
"widget": {
"fizz": "Yes",
"buzz": "Never",
"foo": "Always"
},
"widget": {
"fizz": "Sometimes",
"buzz": "Always",
"foo": "Pending"
}
]
]
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望所有列表以及每个列表都widget被"命名".然而,我首先担心的是,这可能不是合适的JSON.当我将第二个(所需的)JSON片段粘贴到jsonlint.org时,我得到一个解析器错误.
所以首先我要问的是,有人可以如此善良地指出我想要的JSON 应该是什么样才能做到正确; 然后第二个,如果有人可以帮助我widgetGroups按下我的列表,以便Java JSON或GSON可以产生所需的输出.提前致谢!
首先,你确定这是正确的吗?评论和代码不匹配.
// Returns a single List<Widget> with 2 Widgets in it...
List<List<Widget>> widgetGroups = getWidgetGroups();
Run Code Online (Sandbox Code Playgroud)
其次,创建一个WidgetGroup类,它将充当单个WidgetGroup的容器.
public class WidgetGroup {
private String name;
private List<Widget> widgets;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Widget> getWidgets() {
return widgets;
}
public void setWidgets(List<Widget> widgets) {
this.widgets = widgets;
}
}
Run Code Online (Sandbox Code Playgroud)
这将是一个有效的JSON结构:
{
"widgetGroups" : [
{
"widgetGroup": [
"widget": {
"fizz": "Yes",
"buzz": "Never",
"foo": "Always"
},
/*More widgets*/
]
},
/*More widget groups*/
]
}
Run Code Online (Sandbox Code Playgroud)
这样的事情应该有效:
Map<String, List<WidgetGroup>> widgetGroups = new HashMap<String, List<WidgetGroup>>();
WidgetGroup widgetGroup1 = getWidgetGroup(); // Just an assumption of one of your methods.
WidgetGroup widgetGroup2 = getWidgetGroup(); // Just an assumption of one of your methods.
List<WidgetGroup> widgetGroupList = new ArrayList<WidgetGroup>();
widgetGroupList.add(widgetGroup1);
widgetGroupList.add(widgetGroup2);
widgetGroups.put("widgetGroups", widgetGroupList);
Run Code Online (Sandbox Code Playgroud)
然后你打电话toJson()给地图.