Gson 解析Map,數組

1,Gson 解析map

json數據格式爲:{“Ipc0”:{"Address":"192.168.1.12","Password":"admin","UserName":"admin","Port":554},

"Ipc1":{"Address":"192.168.1.12","Password":"admin","UserName":"admin","Port":554},

"Ipc2":{"Address":"192.168.1.12","Password":"admin","UserName":"admin","Port":554}}


將數據解析爲map


private Map<Stirng ,IPCInfo>  getIPCInfo(){

Gson gson = new Gson();

Map<String ,IPCInfo> map = null;

if(isNotEmpty(jsonStr)){

Type type = new TypeToken<Map<String,IPCInfo>>(){}.getType();

map = gson.fromJson(jsonStr,type);

}

return map;

}


2,解析數組轉List

json數據格式爲:{“found”:2,"records":[{"Channel":0,"CreateTime":1481597517,"RecNo":1,"Method":"one"},{"Channel":0,"CreateTime":1481597517,"RecNo":1,"Method":"two"}]}


private <T>List<T> getRecord(){

List<T> list = new ArrayList<>();

try{

if (isNotEmpty(jsonStr)) {

JSONObject   record = new JSONObject (jsonStr);

JSONArray recordArray = record.getJSONArray("records");

list = jsonToArrayList(recordArray.toString(),Record.class);

}

}catch(JSONException e){

e.printStachTrace();

}

return list;

}


private <T>ArrayList<T> jsonToArrayList(String json ,Class<T> clazz){

Type type = new TypeToken<ArrayList<JsonObject>>(){}.getType();

ArrayList<JSONObject> jsonObjects = new Gson().fromJson(json ,type);

ArrayList<T> arrayList = new ArrayList<>();

for (JsonObject jsonObject : jsonObjects){

arrayList.add(new Gson().fromJson(jsonObject ,clazz));

}

return arrayList;

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章