2016-04-04 89 views
0

如何解析嵌套的JSON到Java解析JSON到Java對象4

{  
    "menu": { 
     "id": "file", 
     "value": "File", 
     "popup": { 
      "menuitem": [{ 
       "value": "New", 
       "onclick": "CreateNewDoc" 
      }, { 
       "value": "Open", 
       "onclick": "OpenDoc" 
      }, { 
       "value": "Close", 
      "onclick": "CloseDoc" 
      }] 
     } 
    } 
} 

回答

0

您可以使用其他改性劑,不僅公衆

public class MainMenu { 

    public Menu menu; 

    public class Menu { 

     public String id; 
     public String value; 
     public Popup popup; 

     public class Popup { 

      public List<Item> menuitem; 

      public class Item { 
       public String value; 
       public String onclick; 
      } 

     } 

    } 
} 

public class Example { 

    public static void main(String[] args) { 

     String json =  "{" + 
          "'menu': "+ 
           "{" + 
            "'id': 'file'," + 
            "'value': 'File'," + 
            "'popup': " + 
             "{" + 
              "'menuitem': " + 
               "[{" + 
                "'value': 'New'," + 
                "'onclick': 'CreateNewDoc'" + 
                "}, {" + 
                "'value': 'Open'," + 
                "'onclick': 'OpenDoc'" + 
                "}, {" + 
                "'value': 'Close'," + 
                "'onclick': 'CloseDoc'" + 
               "}]" + 
             "}" + 
           "}" + 
          "}"; 
     Gson gson = new GsonBuilder().setPrettyPrinting().create(); 

     MainMenu mainMenu = gson.fromJson(json, MainMenu.class); 

     System.out.println(gson.toJson(mainMenu)); 
    } 
} 

輸出:

{ 
    "menu": { 
    "id": "file", 
    "value": "File", 
    "popup": { 
     "menuitem": [ 
     { 
      "value": "New", 
      "onclick": "CreateNewDoc" 
     }, 
     { 
      "value": "Open", 
      "onclick": "OpenDoc" 
     }, 
     { 
      "value": "Close", 
      "onclick": "CloseDoc" 
     } 
     ] 
    } 
    } 
} 

Maven依賴關係

<dependency> 
     <groupId>com.google.code.gson</groupId> 
     <artifactId>gson</artifactId> 
     <version>2.4</version> 
    </dependency>