修改json数据中key(键值)

时间:2023-03-10 03:22:02
修改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);
}