fbpx

JSON.equals in Java to compare two JSONs

JSON.areEqual(json1,json2)

The function returns true if the two JSON’s are equals and false if they are unequal. The parameter can be a JSONObject of type org.json.JSONObject or a JSON String.

The JSON utility is available as part of BlobCity Commons

Download JAR | View Source on GitHub

com.blobcity.json.JSON.areEqual("{}", "{}"); -> true
JSON.areEqual("{\"a\": \"1\"}", "{}"); -> false

The function checks for the complete JSON. Every element of the JSON must be equal for the equals check to pass. The following givesĀ areEquals => false

{
  "name": "Tom",
  "country": "USA"
}
{
  "name": "Tom",
  "country": "US"
}

Deeps checks are also support. Nested JSON’s must be equal for the JSON to be equal. The below 2 conditions emails the same.

areEqual => true

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}

areEqual => false

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "My lane"
  }
}

areEqual => false

{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA"
  }
}
{
  "name": "Tom",
  "country": "USA",
  "address": {
    "line1": "Lane 1, USA",
    "zip": "19700"
  }
}

Array comparions are also supported, and array elements must be in same order in both JSON’s for the equals to pass.

areEqual => true

{
  "name": "Tom",
  "roles": ["admin", "user"]
}
{
  "name": "Tom",
  "roles": ["admin", "user"]
}

areEqual => false

{
  "name": "Tom",
  "roles": ["user", "admin"]
}
{
  "name": "Tom",
  "roles": ["admin", "user"]
}

 

%d bloggers like this: