今天在调用第三方接口的时候,我这边需要解析Json来获取想要的数据,Json格式如下:
{
"daaa": {
"results": [
{
"__madaa": {
"id": "ExportSet('')",
"uri": ":844
"type": "rt"
},
"Irid": "",
"NCan": {
"results": [
{
"__madaa": {
"id": "h004')",
"uri": 4')",
"type": "ate"
},
"Pernr": "4",
"StaffNo": "P",
"Ename": "Nik",
"Zgesch": "男",
"Depcode": "S",
"PositionTx": "0",
"Telnr": "",
"Zemail": "",
"Insti": "",
"EducationTx": "",
"Ksbez": "Computer",
"Zpofo": "",
"Zwarning": "",
"Zsick": "d"
}
]
},
"WH": {
"results": [
{
"__madaa": {
"id": "004')",
"uri": "004')",
"type": "tWorkinghistory"
},
"Pernr": "04",
"Begda": "01",
"Endda": "21",
"Depcode": "1",
"DepcodeTx": "S",
"PositionTx": "S",
"FuncGrTx": "",
"Lvltext": "D",
"Btrtl": "Dg"
},
{
"__madaa": {
"id": "55004')",
"uri": "55004')",
"type": "story"
},
"Pernr": "4",
"Begda": "01",
"Endda": "1",
"Depcode": "2",
"DepcodeTx": "nt 02",
"PositionTx": "020",
"FuncGrTx": "",
"Lvltext": "tment",
"Btrtl": "ng"
}
]
}
}
]
}
}
如代码块所示,Json中有3级同名的key=results的数据,且每一级所包含的信息不同
NCan下的results所包含的数据里有Depcode,DepcodeTx,PositionTx等数据代表着目前所在的部门信息
WH下的results同样有Depcode,DepcodeTx,PositionTx等数据代表着历史所在的部门信息
如果业务要求我们同时拿到两种信息,那么我们该怎么解析呢?
如下所示:
调用此方法可以将相同的key改变key值,然后用新的key值存储数据!
public static JSONObject changeJsonObj(JSONObject jsonObj,Map<String, String> keyMap) {
JSONObject resJson = new JSONObject();
Set<String> keySet = jsonObj.keySet();
for (String key : keySet) {
String resKey = keyMap.get(key) == null ? key : keyMap.get(key);
try {
JSONObject jsonobj1 = jsonObj.getJSONObject(key);
resJson.put(resKey, changeJsonObj(jsonobj1, keyMap));
} catch (Exception e) {
try {
JSONArray jsonArr = jsonObj.getJSONArray(key);
resJson.put(resKey, changeJsonArr(jsonArr, keyMap));
} catch (Exception x) {
resJson.put(resKey, jsonObj.get(key));
}
}
}
return resJson;
}
public static JSONArray changeJsonArr(JSONArray jsonArr,Map<String, String> keyMap) {
JSONArray resJson = new JSONArray();
for (int i = 0; i < jsonArr.size(); i++) {
JSONObject jsonObj = jsonArr.getJSONObject(i);
resJson.add(changeJsonObj(jsonObj, keyMap));
}
return resJson;
测试:
Map<String, String> keyMap = new HashMap<String, String>();
//将历史工作经历的部门、职位修改为:
keyMap.put("Depcode", "DepcodeHistory");
keyMap.put("PositionTx", "PositionTxHistory");
//jsonArray.toJSONString()) 代表历史部门WH的JSON串
jsonObj = changeJsonObj(JSONObject.parseObject(jsonArray.toJSONString()),keyMap);
如果有帮助到你,希望留下你的点赞和关注!