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