Skip to content

Instantly share code, notes, and snippets.

@goyalzz
Last active January 9, 2021 18:33
Show Gist options
  • Save goyalzz/95c58862f54cee57ae68e58bee2378f2 to your computer and use it in GitHub Desktop.
Save goyalzz/95c58862f54cee57ae68e58bee2378f2 to your computer and use it in GitHub Desktop.
Compare two JSON Objects and get Difference.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.stereotype.Service;
public class JsonUtils {
public static Object jsonsEqual(Object obj1, Object obj2) throws JSONException {
JSONObject diff = new JSONObject();
if (!obj1.getClass().equals(obj2.getClass())) {
return diff;
}
if (obj1 instanceof JSONObject && obj2 instanceof JSONObject) {
JSONObject jsonObj1 = (JSONObject) obj1;
JSONObject jsonObj2 = (JSONObject) obj2;
List<String> names = new ArrayList(Arrays.asList(JSONObject.getNames(jsonObj1)));
List<String> names2 = new ArrayList(Arrays.asList(JSONObject.getNames(jsonObj2)));
if (!names.containsAll(names2) && names2.removeAll(names)) {
for (String fieldName : names2) {
if(jsonObj1.has(fieldName))
diff.put(fieldName, jsonObj1.get(fieldName));
else if(jsonObj2.has(fieldName))
diff.put(fieldName, jsonObj2.get(fieldName));
}
names2 = Arrays.asList(JSONObject.getNames(jsonObj2));
}
if (names.containsAll(names2)) {
for (String fieldName : names) {
Object obj1FieldValue = jsonObj1.get(fieldName);
Object obj2FieldValue = jsonObj2.get(fieldName);
Object obj = jsonsEqual(obj1FieldValue, obj2FieldValue);
if (obj != null && !checkObjectIsEmpty(obj))
diff.put(fieldName, obj);
}
}
return diff;
} else if (obj1 instanceof JSONArray && obj2 instanceof JSONArray) {
JSONArray obj1Array = (JSONArray) obj1;
JSONArray obj2Array = (JSONArray) obj2;
if (!obj1Array.toString().equals(obj2Array.toString())) {
JSONArray diffArray = new JSONArray();
for (int i = 0; i < obj1Array.length(); i++) {
Object obj = null;
matchFound: for (int j = 0; j < obj2Array.length(); j++) {
obj = jsonsEqual(obj1Array.get(i), obj2Array.get(j));
if (obj == null) {
break matchFound;
}
}
if (obj != null)
diffArray.put(obj);
}
if (diffArray.length() > 0)
return diffArray;
}
} else {
if (!obj1.equals(obj2)) {
return obj2;
}
}
return null;
}
private static boolean checkObjectIsEmpty(Object obj) {
if (obj == null)
return true;
String objData = obj.toString();
if (objData.length() == 0)
return true;
if (objData.equalsIgnoreCase("{}"))
return true;
return false;
}
}
@aajane
Copy link

aajane commented Aug 28, 2018

Its not working at all. Its just showing a blank screen

@aajane
Copy link

aajane commented Aug 28, 2018

could you be more specific, perhaps by using example?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment