Parsing a complex Json Object using GSON in Java

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());  
}

Leave a Comment