[英]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. 我在Java中使用
org.json
库在我的Java程序中读取json文件。 I've written the following method to compare two JSON Objects using equals
method. 我编写了以下方法,使用
equals
方法比较两个JSON对象。 However it always returns false even though both objects are the same. 但是,即使两个对象相同,它始终返回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;
}
When I run this method it always returns false
当我运行此方法时,它总是返回
false
The json object I'm comparing is 我正在比较的json对象是
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? 您是否使用JSON-Java库?
JSONArray does not implement equals()
therefore JSONArray不实现
equals()
if(contentArray1.equals(contentArray2))
always returns false, if contentArray1 != contentArray2
. 如果
contentArray1 != contentArray2
,则始终返回false。
Strangely you need to use the similar() method defined by JSONArray to make it work: 奇怪的是,您需要使用JSONArray定义的like()方法来使其工作:
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. 比较两个数组是否相等(即使元素相同)也将返回false,因为您实际上是在比较地址,除非JSONArray具有显式的equals方法。
Rather, compare each element of the array for equality. 相反,比较数组的每个元素是否相等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.