//方法一:修改JSONObject的键

public static JSONObject changeJsonObj(JSONObject jsonObj,Map keyMap) {

JSONObject resJson = new JSONObject();

Set 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 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 map = new HashMap<>();

map.put("latitude","lat");

map.put("longitude","lng");

List list = new ArrayList();

Map 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);

}

Logo

DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。

更多推荐