如何为下面的 JSON 脚本为 gson
创建 javabean?
{
"header": [
{
"title": {
"attempts": 3,
"required": true
}
},
{
"on": {
"next": "abcd",
"event": "continue"
}
},
{
"on": {
"next": "",
"event": "break"
}
}
]
}
我正在尝试为此 JSON 输出构建 javabean。我无法在 on
上重复字段名称。
请提出任何解决方案。
最佳答案
您将需要多个类来完成此任务。我对命名做了一些假设,但这些应该足够了:
public class Response {
private List<Entry> header;
private class Entry {
private Title title;
private On on;
}
private class Title {
int attempts;
boolean required;
}
private class On {
String next, event;
}
}
您可以使用 main()
方法对其进行测试,例如:
public static void main(String[] args) {
// The JSON from your post
String json = "{\"header\":[{\"title\":{\"attempts\":3,\"required\":true}},{\"on\":{\"next\":\"abcd\",\"event\":\"continue\"}},{\"on\":{\"next\":\"\",\"event\":\"break\"}}]}";
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Response response = gson.fromJson(json, Response.class);
System.out.println(response.header.get(0).title.attempts); // 3
System.out.println(response.header.get(1).on.next); // abcd
System.out.println(gson.toJson(response)); // Produces the exact same JSON as the original
}
关于java - 使用 gson 创建复杂的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31515363/