Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/396.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/assembly/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用org.JSON库比较Java中的JSON对象_Java_Json - Fatal编程技术网

使用org.JSON库比较Java中的JSON对象

使用org.JSON库比较Java中的JSON对象,java,json,Java,Json,我使用java中的org.json库读取java程序中的json文件。我编写了以下方法,使用equals方法比较两个JSON对象。但是,即使两个对象相同,它也总是返回false private boolean isContentEqual(JSONObject o1, JSONObject o2) { boolean isContentEqual = false; try { JSONArray contentArray1 = o1.getJSONArray("c

我使用java中的
org.json
库读取java程序中的json文件。我编写了以下方法,使用
equals
方法比较两个JSON对象。但是,即使两个对象相同,它也总是返回false

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;
}
当我运行这个方法时,它总是返回
false

我正在比较的json对象是

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

为什么会发生这种情况?

比较两个数组是否相等,即使元素相同,也会返回false,因为您实际上是在比较地址,除非JSONArray有一个显式的equals方法

相反,比较数组中的每个元素是否相等。

是否使用库

因此,JSONArray不实现
equals()

if(contentArray1.equals(contentArray2))
如果
contentArray1!=contentArray2

奇怪的是,您需要使用JSONArray定义的类似()方法使其工作:

if(contentArray1.similar(contentArray2))

你确定JSON对象的初始化正确吗?@andrewdleach:是的。