jsonobject修改key的值_修改json数据中key(键值)//⽅法⼀:修改JSONObject的键
public static JSONObject changeJsonObj(JSONObject jsonObj,Map keyMap) {
JSONObject resJson = new JSONObject();
Set keySet = jsonObj.keySet();
for (String key : keySet) {
String resKey = (key) == null ? key : (key);
resJson.put((key));
try {
if ((key) instanceof JSONObject) {
JSONObject jsonobj1 = (JSONObject) (key);
resJson.put(resKey, changeJsonObj(jsonobj1, keyMap));
} else if ((key) instanceof JSONArray) {
JSONArray jsonArr = (JSONArray) (key);
resJson.put(resKey, changeJsonArr(jsonArr, keyMap));
object to
} else (key) instanceof ResponseHelper){
//封装的实体类
//将实体类转换为json格式,修改实体类的键
Object obj = JSON((ResponseHelper) (key));
resJson.put(resKey, changeJsonObj(JSONObject.String()), keyMap));
} else {
resJson.put(resKey, (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 = JSONObject(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);
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。