Home > database >  Compare if a JSON contains subset of another JSON in Java
Compare if a JSON contains subset of another JSON in Java

Time:08-25

How can I compare if a generic JSON is included in another generic json in Java

For Example JSON 1 :

{ "id": "1", "name": "Michael Jordan", "age": "50" }

JSON 2 :

{ "name": "Michael Jordan" }

So if JSON 2 contains matches the key and value pair in JSON 1 ignoring the other attributes the program should return true or else false.

Currently Using this Solution: https://stackoverflow.com/a/31858585/19840742

But it's a hit or miss situation working sometimes and sometimes don't as I need to pickup the json values from a excel sheet.

CodePudding user response:

If you are using org.json.JSONObject, then it is super easy.

public static boolean isSubset(JSONObject superset, JSONObject subset) {
    return new JSONObject(superset, JSONObject.getNames(subset)).similar(subset);
}

CodePudding user response:

If your objects implement the Map interface, like JsonObject in JSR-374 does, you can use

public boolean isSubset(JsonObject superset, JsonObject subset) {
    return superset.entrySet().containsAll(subset.entrySet());
}
  • Related