简体   繁体   中英

Compare two json strings and print differences between them using Java

I have two json strings and I would like to compare string2 with string1 and print where they differ.

For example:

expectedJson : {"Products":{"Product":[{product_name":"string""unit_cost":"string"}],"Region":["string"]}}

inputJson: {"Products":{"Product":[{product_name":"string""unit_cost":"number"}],"Region":["string"]}}

The comparison result should be something like: Differences: "unit_cost":"number"

I am using JSONP (javax) libraries to read and parse the input JSON payload and building the above (inputJosn) string and now would like to compare that with the actual expected json schema (actualJson) string.

Any thoughts or inputs on this please?

You can instantiate those json objects as java POJOs and have a method or a static method in the class to compare and provide the results you need.

1- Write a class that replicates the structure of the json you are receiving. As you have a list you may need to write more than one class so you can have attributes that replicate the arrays, for example:

public ClassA{
    ArrayList<ClassB> bClassObjectList;
    ...
    <getters and setters>
}

public ClassB{
 ...      
}

2- Add public getters and setters for all the properties of your classes

3- Use Gson library to unserialize the json strings (expected and received) into objects or the top class you wrote.

4- Write a static method in the top class to compare the object and return the result you need.

This could be one way to implement the static method to do the comparison, you can do it totally different depending on your needs.

public static final ArrayList<String> tellMeTheDifferenceBetween(ClassA obj1, ClassA obj2){
    ArrayList<String> rtn = new ArrayList<>();

    if(!ojb1.getProp1().equals(obj2.getProp2)){
         rtn.add("Prop1_is_different");
    }

    if(ojb1.getProp2() != obj2.getProp2){
         rtn.add("Prop2_is_different");
    }

    ...

    return rtn;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM