实体转换json时根据模板去除相应字段

本文介绍了一个基于JSON模板的工具,该工具可以根据指定的模板动态生成不同形式的报文,支持灵活地添加或移除字段,适用于需要根据不同场景生成多样化报文的工作场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

工作中需要用同一个实体生成多种形式报文,中间某些字段或传或不传,写了个根据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);
            }
        });
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值