简体   繁体   中英

Comparing JSON objects in Java using org.json library

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?

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM