importjava.util.HashMap;importjava.util.Map;importjava.util.Set;importcom.alibaba.fastjson.JSONArray;importcom.alibaba.fastjson.JSONObject;/***
* 对json数据key进行替换*/
public classJSONUtil {public static JSONObject changeJsonObj(JSONObject jsonObj,MapkeyMap) {
JSONObject resJson= newJSONObject();
Set 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));
}
}
}returnresJson;
}public static JSONArray changeJsonArr(JSONArray jsonArr,MapkeyMap) {
JSONArray resJson= newJSONArray();for (int i = 0; i < jsonArr.size(); i++) {
JSONObject jsonObj=jsonArr.getJSONObject(i);
resJson.add(changeJsonObj(jsonObj, keyMap));
}returnresJson;
}public static voidmain(String[] args) {
String jsonStr= "{\"user\":{\"name\":\"张三\",\"sex\":\"男\",\"hobby\":[{\"motion\":\"足球\",\"desc\":\"任性\"},{\"game\":\"英雄联盟\",\"desc\":\"就是这么任性\"}]}}";
Map keyMap = new HashMap();
keyMap.put("name", "XingMing");
keyMap.put("user", "YongHu");
keyMap.put("desc", "MiaoShu");
JSONObject jsonObj=JSONUtil.changeJsonObj(JSONObject.parseObject(jsonStr),keyMap);
System.out.println("换值结果 》》 " +jsonObj.toString());
}
}