工作中需要用同一个实体生成多种形式报文,中间某些字段或传或不传,写了个根据json模板剔除相应字段的工具
public class JsonTemplate {
public static String transForm(String template,Object sourceObject){
Object templateObject=JSON.parse(template);
if(sourceObject instanceof JSONArray){
loopJsonArray((JSONArray)templateObject,(JSONArray)sourceObject);
}else{
loopJson((JSONObject) templateObject,(JSONObject)sourceObject);
}
return JSON.toJSONString(sourceObject, SerializerFeature.WriteMapNullValue);
}
public static void loopJson(JSONObject template,JSONObject source){
//遍历json 剔除template中不存在的属性
List<String> removeKeys=new CopyOnWriteArrayList<>();
source.entrySet().parallelStream().forEach(entry->{
if(entry.getValue() instanceof JSONArray){
//jsonArray
JSONArray jsonArray= (JSONArray) entry.getValue();
JSONArray templateArray= (JSONArray) template.get(entry.getKey());
if(templateArray==null){
removeKeys.add(entry.getKey());
}else{
loopJsonArray(templateArray,jsonArray);
}
}else if(entry.getValue() instanceof JSONObject){
//jsonObject
JSONObject templateObject=(JSONObject) template.get(entry.getKey());
if(templateObject==null){
removeKeys.add(entry.getKey());
}else{
loopJson(templateObject,(JSONObject) entry.getValue());
}
}else{
//末端节点
if(!template.containsKey(entry.getKey())){
removeKeys.add(entry.getKey());
}
}
});
for(String removeKey:removeKeys){
source.remove(removeKey);
}
}
public static void loopJsonArray(JSONArray template,JSONArray source){
Object firstObject= template.get(0);
Arrays.stream(source.toArray()).parallel().forEach(object->{
if(object instanceof JSONObject){
loopJson((JSONObject) firstObject, (JSONObject) object);
}else if(object instanceof JSONArray){
loopJsonArray((JSONArray) firstObject, (JSONArray) object);
}
});
}
}