In this article I am going to explain how to compare JSON with JAVA using Google-json library. The basic part of the JSON is JsonElement. There are 4 types JSON elements.
  1. Json Object : Surrounded with curly braces and have child JSON elements
  2. Json Primitive Element : It contains field name and it's value
  3. Json Array Element : It contains field name and array of JSON elements.
  4. Json Null Element : It contains nothing 

Implementation Concept

We can call 2 JSON Elements are equalm, when both elements's type and values are equal. Observe below flow chart
  1. Read input json elements as json1, json2
  2. Verify whether element type matches or not
  3. If both elements are objects, then iterate them as key-value pairs, compare its values
  4. If both elements are arrays, then compare its values with indexes
  5. If both elements are primitive, compare its values directly
  6. If both elements are null, no need of any comparison, both are equal

Java Program

Find below for java program
import java.io.StringReader;
import java.util.Map.Entry;
import java.util.Set;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class CompareJSON {
    public static void main(String[] args) {
        JsonParser parser = new JsonParser();
        // JSON String
        String json1 = "{" + "\"age\":100," 
                + "\"name\":\"srinivas\","
                + "\"school\":\"\","
                + "\"messages\":[\"msg 1\",\"msg 2\",\"msg 3\"]}";
        String json2 = "{" + "\"age\":10," 
                + "\"name\":\"srinivas\","
                + "\"school\":\"\","
                + "\"messages\":[\"msg 1\",\"msg 2\"]}";
        
        JsonElement jsonElement1 = parser.parse(new StringReader(json1));
        JsonElement jsonElement2 = parser.parse(new StringReader(json2));
        System.out.println(compareJson(jsonElement1, jsonElement2));
                
    }

    public static boolean compareJson(JsonElement json1, JsonElement json2) {
        boolean isEqual = true;
        // Check whether both jsonElement are not null
        if(json1 !=null && json2 !=null) {
            
            // Check whether both jsonElement are objects
            if (json1.isJsonObject() && json2.isJsonObject()) {
                Set<Entry<String, JsonElement>> ens1 = ((JsonObject) json1).entrySet();
                Set<Entry<String, JsonElement>> ens2 = ((JsonObject) json2).entrySet();
                JsonObject json2obj = (JsonObject) json2;
                if (ens1 != null && ens2 != null && (ens2.size() == ens1.size())) {
                    // Iterate JSON Elements with Key values
                    for (Entry<String, JsonElement> en : ens1) {
                        isEqual = isEqual && compareJson(en.getValue() , json2obj.get(en.getKey()));
                    }
                } else {
                    return false;
                }
            } 
            
            // Check whether both jsonElement are arrays
            else if (json1.isJsonArray() && json2.isJsonArray()) {
                JsonArray jarr1 = json1.getAsJsonArray();
                JsonArray jarr2 = json2.getAsJsonArray();
                if(jarr1.size() != jarr2.size()) {
                    return false;
                } else {
                    int i = 0;
                    // Iterate JSON Array to JSON Elements
                    for (JsonElement je : jarr1) {
                        isEqual = isEqual && compareJson(je , jarr2.get(i));
                        i++;
                    }   
                }
            }
            
            // Check whether both jsonElement are null
            else if (json1.isJsonNull() && json2.isJsonNull()) {
                return true;
            } 
            
            // Check whether both jsonElement are primitives
            else if (json1.isJsonPrimitive() && json2.isJsonPrimitive()) {
                if(json1.equals(json2)) {
                    return true;
                } else {
                    return false;
                }
            } else {
                return false;
            }
        } else if(json1 == null && json2 == null) {
            return true;
        } else {
            return false;
        }
        return isEqual;
    }
}

13 comments:

  1. good code. but how to get the diff?

    ReplyDelete
  2. Compare JSON with java using google GSON library and more to just start to compare with the coding is not possible for anyone. I don't think so best essay help for these pages is just not be share for you at the live library.

    ReplyDelete
  3. What ethical essay topics do you think are the best to write on? I am looking for advice. I have to pick up one topic and start writing on it. I am still doubting.

    ReplyDelete
  4. Full satisfaction from help essay the service. We care that our customers are satisfied with the attitude of our company representatives

    ReplyDelete
  5. They are not able to gather ideas, come up with a problem or theme to work on. write my assignment We can call 2 JSON Elements are equalm, when both elements's type and values are equal. Observe below flow chart

    ReplyDelete
  6. In case you have a complex assignment, finding https://www.privatewriting.com/custom-research-paper the available expert can take a couple of days as well. If this is your first time ordering from us or you are in a hurry, choosing the best available writer is a smart thing to do.

    ReplyDelete
  7. Matching deposit bonus means that the house will match your deposit and include the chips to your account here. This is great in terms of support and it is particularly useful for new players because it will boost their confidence and relieve the tension.

    ReplyDelete
  8. Hello, I would like to thank you for sharing this interesting information. I appreciate reading it. The material you have provided here will be useful for a lot of people, especially for the programmers, I will tell about this post to my friend. I was actually looking for a place where I can buy a discussion post. Nevertheless, thanks a lot.

    ReplyDelete
  9. Honestly, I am not so sure I understood everything, but it helped me with my assignment, at least (being late to class because you simply don't want to go, as you know you're not ready with your homework... a nightmare, really).

    ReplyDelete
  10. The main thing in an essay is the presence of a clearly marked author's "I" in the reflections on a given topic, the presence of a clearly expressed attitude to the issue of concern. The specific semantic content of the work of this genre is fully determined by its type. Thus, https://en.writingapaper.net/edit-my-paper/ if the subject of reasoning concerns history, then the essay may be based on a global reflection on the consequences of revolutions and wars, or an assessment of specific significant events from the point of view of the author.

    ReplyDelete
  11. Formation of the practical chapter - here it is important to note the following points: to give a brief description of the activity of the object of best paper writing service reviews research, identify its strengths and weaknesses with a focus on the topic, conduct a qualitative analysis or identify and prove the problem, the need for its solution.

    ReplyDelete

Blogroll

Popular Posts