2

I'm using org.json library in java to read a json file in my java program. I've written the following method to compare two JSON Objects using equals method. However it always returns false even though both objects are the same.

private boolean isContentEqual(JSONObject o1, JSONObject o2) {
    boolean isContentEqual = false;
    try {
        JSONArray contentArray1 = o1.getJSONArray("content");
        JSONArray contentArray2 = o2.getJSONArray("content");
        if (contentArray1.equals(contentArray2))
            isContentEqual = true;
        else
            isContentEqual = false;
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    return isContentEqual;
}

When I run this method it always returns false

The json object I'm comparing is

content: [
    {
        one: "sample text 1",
        two: ""
    },
    {
        one: "sample text 2",
        two: ""
    },
    {
        one: "sample text 3",
        two: ""
    },
    {
        one: "sample text 4",
        two: ""
    }
]

Why is this happening?

2
  • Are you certain that the JSON objects are initialized correctly? Commented Jul 15, 2015 at 20:18
  • @andrewdleach : yes I am. Commented Jul 15, 2015 at 20:19

2 Answers 2

4

Do you use JSON-Java library?

JSONArray does not implement equals() therefore

if(contentArray1.equals(contentArray2))

always returns false, if contentArray1 != contentArray2.

Strangely you need to use the similar() method defined by JSONArray to make it work:

if(contentArray1.similar(contentArray2))
Sign up to request clarification or add additional context in comments.

Comments

0

Comparing two arrays for equality even if the elements are the same will return false because you are essentially comparing the addresses unless JSONArray has an explicit equals method.

Rather, compare each element of the array for equality.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.