1.场景:

 比较两个json Bean 对象 的不同之处:

之前的处理方式是反射,比较field 值:

 

依赖: jackson-databind-2.9.3.jar

       <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.24</version>
        </dependency>

  <flipkart.version>0.4.8</flipkart.version>

<dependency>
<groupId>com.flipkart.zjsonpatch</groupId>
<artifactId>zjsonpatch</artifactId>
<version>${flipkart.version}</version>
</dependency>

 

eg:

    private String filterChanged(String afterString,String value) {
        log.info("Filtering changed values");
        String beforeString = mongoDBDao.find(dbName,collectionName,Constant.BOOKING_NO,value);
        log.info("The before string {}",beforeString);
        log.info("The after string {}",afterString);
        ObjectMapper jackson = new ObjectMapper();
        JsonNode patchNode = null;
        try {
            JsonNode beforeNode = jackson.readTree(beforeString);
            JsonNode afterNode = jackson.readTree(afterString);
            patchNode = JsonDiff.asJson(beforeNode, afterNode);
        } catch (IOException e) {
            exceptionHandlingUtils.throwJSONConvertException(e);
        }
        String diff = patchNode.toString();
        if(patchNode.isArray()){
            JSONArray jsonArray = JSONArray.parseArray(diff);
            List<Object> collect=jsonArray.stream()
                    .map(obj->{
                        JSONObject jsonObject = JSONObject.parseObject(obj.toString());
                        String path = (String)JSONPath.eval(jsonObject,"$.path");
                        if((Constant.PREFIX_HISTORY_ID.equals(path))
                                || Constant.PREFIX_BOOKING_NO.equals(path)
                                || Constant.PREFIX_TIMESTAMP.equals(path)
                                || Constant.PREFIX_REQUEST_ID.equals(path)
                                || path.contains(AUOGetBookingEventBCConstant.DATA_EVENT)){
                            return null;
                        }
                                return obj;
                    })
                    .collect(Collectors.toList());
            collect.removeAll(Collections.singleton(null));
            diff = JSON.toJSONString( //json 序列化时生成标准的hjson格式
                    collect,
                    SerializerFeature.PrettyFormat,
                    SerializerFeature.SortField); //按照对象的默认顺序排序
        }else{
            log.error("****Can't parse the patch node****");
            throw new UnsupportedOperationException("The kind of return value is not supported");
        }
        log.info("Diff value between the two json is {}",diff);
        return diff;
    }

 

posted on 2019-07-30 17:23  lshan  阅读(1658)  评论(0编辑  收藏  举报