Parsing a complex Json Object using GSON in Java

后端 未结 1 875
借酒劲吻你
借酒劲吻你 2020-12-02 23:27

I have a very long JSON to parse with Gson, but for brevity I have trimmed it to this example:

{
 \"volumes\": [
  {
   \"status\": \"available\", 
   \"mana         


        
相关标签:
1条回答
  • 2020-12-02 23:50

    First problem: your VolumeContainer needs to be:

    public class VolumeContainer {
       public List<Volume> volumes;
    }
    

    it does not need to be static.

    Second problem: your Volume class should be like this:

    public class Volume {
      private String status; 
      private Boolean managed; 
      private String name; 
      private Support support; 
      private String storage_pool; 
      private String id; 
      private int size;
      private List<String> mapped_wwpns;
    
      public String getId(){return id;}
      public String getName(){return name;}
    }
    

    I defined a class named Support like this:

    public class Support {
       private String status;
       private List<String> reasons;
    }
    

    Third problem: parsing, If response string contains your example data, simply parse like this:

    Gson g = new Gson();
    VolumeContainer vc = g.fromJson(response, VolumeContainer.class);
    

    Fourth problem: get the map. Finally to get your HashMap, just do like this:

    HashMap<String, String> hm = new HashMap<String,String>();
    for(Volume v: vc.volumes){
      hm.put(v.getId(), v.getName());  
    }
    
    0 讨论(0)
提交回复
热议问题