修改json數據中key(鍵值)

//方法一:修改JSONObject的鍵

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);
resJson.put(resKey,jsonObj.get(key));
try {
if (jsonObj.get(key) instanceof JSONObject) {
JSONObject jsonobj1 = (JSONObject) jsonObj.get(key);
resJson.put(resKey, changeJsonObj(jsonobj1, keyMap));
} else if (jsonObj.get(key) instanceof JSONArray) {
JSONArray jsonArr = (JSONArray) jsonObj.get(key);
resJson.put(resKey, changeJsonArr(jsonArr, keyMap));
} else if(jsonObj.get(key) instanceof ResponseHelper){  
       //封裝的實體類
       //將實體類轉換爲json格式,修改實體類的鍵
Object obj = JSONArray.toJSON((ResponseHelper) jsonObj.get(key));
resJson.put(resKey, changeJsonObj(JSONObject.parseObject(obj.toString()), keyMap));
} else {
resJson.put(resKey, jsonObj.get(key));
}
} catch (Exception e) {
e.printStackTrace();
}
}
return resJson;
}

//方法二:修改JSONArray的鍵
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;
}

//測試方法:
//測試數據格式大致爲: {"info":{"data":[{"lng":"333","lat":"3"}],"count":1}}
//備註:如果實體類中數據latitude爲null,則轉換時,控制檯打印不出來轉換後的數據
public static void main(String[] args) {
String json = "{\"areaid\":\""+1+"\"}";

Map<String,String> map = new HashMap<>();
map.put("latitude","lat");
map.put("longitude","lng");

List list = new ArrayList();
Map<String,String> maplist2 = new HashMap<>();
maplist2.put("latitude","3");
maplist2.put("longitude","333");
list.add(maplist2);
ResponseHelper helper = new ResponseHelper(list,list.size());
JSONObject sgxcjson = new JSONObject();
sgxcjson.put("info", helper);

JSONObject jsonObject = SfApplicationTests.changeJsonObj(sgxcjson,map);
System.out.println(jsonObject);
}





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