且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在 Java 中使用 GSON 解析复杂的 Json 对象

更新时间:2023-01-17 17:48:34

第一个问题:你的VolumeContainer需要是:

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

它不需要是静态的.

第二个问题:你的Volume类应该是这样的:

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

我像这样定义了一个名为 Support 的类:

I defined a class named Support like this:

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

第三个问题:解析,如果response字符串包含你的示例数据,简单的解析如下:

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

第四个问题:获取地图.最后得到你的 HashMap,就像这样:

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