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.
- Json Object : Surrounded with curly braces and have child JSON elements
- Json Primitive Element : It contains field name and it's value
- Json Array Element : It contains field name and array of JSON elements.
- 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
- Read input json elements as json1, json2
- Verify whether element type matches or not
- If both elements are objects, then iterate them as key-value pairs, compare its values
- If both elements are arrays, then compare its values with indexes
- If both elements are primitive, compare its values directly
- 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; } }
good code. but how to get the diff?
ReplyDeletewhat if JSON order changes ?
ReplyDeleteCompare 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.
ReplyDeleteWhat 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.
ReplyDeleteFull satisfaction from help essay the service. We care that our customers are satisfied with the attitude of our company representatives
ReplyDeleteThey 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
ReplyDeleteIn 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.
ReplyDeleteMatching 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.
ReplyDeleteHello, 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.
ReplyDeleteHonestly, 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💰Get free 250$ on Ysense trusted network without investment
ReplyDelete📢 Join Crypto quantum leap world's famous online Crypto course
🦷 Read Secret teeth care tips
About
Teeth whitening,
Teeth decay,
Teethsche,
African American should pay less on payroll taxes because most of them do not have access to employment like the majority of the whites and also they lack access to such programs in general.
ReplyDeletetheology assignment help
leading assignment help website
microservices architecture
capstone project help
article writer for hire
hire a content writer
content writing service
freelance writers for hire
ghost writers for hire
write my assignment for me
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.
ReplyDeleteFormation 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