前言:由于使用fastjson默认会对null值进行过滤,导致该null值对应的字段丢失,处理起来相对麻烦,故选择net.sf.json
第一步,先引入net.sf.json包,其他依赖请自行百度搜索
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier><!-- 指定jdk版本 -->
</dependency>
第二步,拿到要操作的map类型的json对象
JSONObject map = JSONObject.fromObject(data);
if(map.isNullObject()) return DES.encrypt("null");
Set<String> keySet = map.keySet();
for (String s : keySet) {
map.put(s, dealWithRecursion(map.get(s)));
}
第三步,编写递归方法/**
* 递归循环json字符串
* @param object
* @return
* @throws Exception
*/
private Object dealWithRecursion(Object object) throws Exception{
if(object instanceof JSONObject){
JSONObject jsonObject = (JSONObject) object;
if(jsonObject.isNullObject()) return DES.encrypt("null");
Set keySet = jsonObject.keySet();
for (Object o : keySet) {
if (jsonObject.get(o) instanceof JSONObject) {
JSONObject ooo = (JSONObject) jsonObject.get(o);
if(ooo.isNullObject()){
jsonObject.put(o,DES.encrypt("null"));
}else{
dealWithRecursion(jsonObject.get(o));
}
} else if (jsonObject.get(o) instanceof JSONArray){
dealWithRecursion(jsonObject.get(o));
} else {
jsonObject.put(o,DES.encrypt(jsonObject.get(o)+""));
}
}
return jsonObject;
} else if(object instanceof JSONArray){
List<Object> list = new ArrayList<>();
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.size(); i++) {
Object o = jsonArray.get(i);
list.add(dealWithRecursion(o));
}
return list;
} else {
return DES.encrypt(object+"");
}
}
注意事项:
jsonObject.isNullObject()这个方法是判断对象是否为null的,如果不做判断会出现null值异常