2015-07-20 39 views
1

如何为以下JSON脚本创建用于gson的javabean?使用gson创建复杂的json对象

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

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

请提出任何解决方案。

+0

好吧,你的问题是:

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()方法类似测试吗? –

+0

我想通过gson构建上面的json脚本。为此,我无法创建java bean – Martin

+0

我得到错误多个字段名称与“否” – Martin

回答

1

您将需要多个类来完成此操作。我做了命名的一些假设,但这些应该足够了:

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 
} 
+0

它的作品像魅力。 – Martin