Android map 存對象並且解析(超級簡單)

多的不說,直接上代碼,真心簡單:

先定義一個實體類:

public class ObjectFilesInfo implements Serializable {
	
 String name;
 String vaule;

  public ObjectFilesInfo(String name, String vaule) {
    	this.name = name;
   	 this.vaule = vaule;
   }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getVaule() {
        return vaule;
    }

    public void setVaule(String vaule) {
        this.vaule = vaule;
    }
}

這是Map:

Map<String, ObjectFilesInfo> objectMap = new HashMap<>();
objectMap.put("G000006", new ObjectFilesInfo("名字", "jimTerency"));
objectMap.put("G000007", new ObjectFilesInfo("年齡", "28"));
objectMap.put("G000008", new ObjectFilesInfo("性別", "男"));
objectMap.put("G000009", new ObjectFilesInfo("薪資", "1000萬/年"));
Gson gson = new Gson();
String mapJson = gson.toJson(objectMap);

那怎麼解析呢?

//將JSON 轉換爲map

java.lang.reflect.Type type = new 
TypeToken<HashMap<String,ObjectFilesInfo>>() {
}.getType();

Gson gson = new Gson();
Map<String, ObjectFilesInfo> objectMap = gson.fromJson(mapJson,type );
Set<Map.Entry<String, ObjectFilesInfo>> entrys = objectMap.entrySet();

for(Map.Entry<String, ObjectFilesInfo> entry:entrys){
	System.out.println(entry.getKey());// G000006,G000007等
	ObjectFilesInfo objectFilesInfo=  entry.getValue();
	System.out.println(objectFilesInfo.getName();// 名字等
   	System.out.println(objectFilesInfo.getVaule());// jimTerency等
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章