使用gson创建复杂的json对象

时间:2015-07-20 11:30:42

标签: java json gson javabeans

如何为以下JSON脚本创建gson的javabean?

{
    "header": [
        {
            "title": {
                "attempts": 3,
                "required": true
            }
        },
        {
            "on": {
                "next": "abcd",
                "event": "continue"
            }
        },
        {
            "on": {
                "next": "",
                "event": "break"
            }
        }
    ]
}

我正在尝试为此JSON输出构建javabean。我无法重复字段名on

请建议任何解决方案。

1 个答案:

答案 0 :(得分:1)

您需要多个课程才能完成此任务。我对命名做了一些假设,但这些应该足够了:

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
}