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  getIPCInfo(){

Gson gson = new Gson();

Map map = null;

if(isNotEmpty(jsonStr)){

Type type = new TypeToken>(){}.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 List getRecord(){

List 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 ArrayList jsonToArrayList(String json ,Class clazz){

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

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

ArrayList arrayList = new ArrayList<>();

for (JsonObject jsonObject : jsonObjects){

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

}

return arrayList;

}

你可能感兴趣的:(gson,map)