我有 2 个充满整数的 JSONArray。
我想比较它们的相同内容,而不考虑顺序。
所以:
[1, 2] == [1, 2] 正确 [1, 2] == [2, 1] 正确
JSONArray 有
public boolean equals(Object o)
但对于 [1, 2] == [2, 1],它返回 FALSE
所以,我自己推出了:
public boolean isEqual(JSONArray inputJsonArray,
JSONArray outputJsonArray) throws JSONException{
boolean equal=true, done;
int idx = 0;
if (inputJsonArray.length() == outputJsonArray.length()){
//make sure all elements in input array are in output array
done=false;
while (!done){
if(idx >= inputJsonArray.length()){
done=true;
}
else if (isIntInJsonArray(outputJsonArray,
inputJsonArray.getInt(idx)) == false){
equal = false;
done=true;
}
else{
idx ++;
}
}
if (equal){
//make sure all elements in output array are in input array
done=false;
while (!done){
if (idx >= outputJsonArray.length()){
done=true;
}
else if (isIntInJsonArray(inputJsonArray,
outputJsonArray.getInt(idx)) == false){
equal = false;
done=true;
}
else{
idx++;
}
}
}
}
else{
equal = false;
}
return equal;
}
基本上,我检查两个 JSONArray 的长度是否相同。如果是,那么我确保 outputJsonArray 中的每个元素都在 inputJsonArray 中,反之亦然。执行此操作的主要方法是:
private boolean isIntInJsonArray(JSONArray inputJsonArray, int mInt) throws JSONException{
boolean found=false, done=false;
int idx = 0;
while (!done){
if(idx >= inputJsonArray.length()){
done=true;
}
else if (inputJsonArray.getInt(idx) == mInt){
found = true;
done=true;
}
else{
idx ++;
}
}
return(found);
}
这对我来说就像是大量的代码。有谁知道是否有更简单的方法来做到这一点?
最佳答案
将数组转换为 JSONObject
,然后使用其 equals
方法。
JSONArray arr1 = new JSONArray();
JSONArray arr2 = new JSONArray();
arr1.put(1);
arr1.put(2);
arr1.put(3);
arr1.put(4);
arr1.put(5);
arr2.put(2);
arr2.put(1);
arr2.put(3);
arr2.put(5);
arr2.put(4);
JSONObject o1 = arr1.toJSONObject(arr1);
JSONObject o2 = arr2.toJSONObject(arr2);
System.out.println(o1.equals(o2)); //true
查看JSONObject
的源代码,它使用其底层映射来检查相等性。
@Override
public boolean equals(Object obj) {
if (obj instanceof JSONObject) {
return myHashMap.equals(((JSONObject)obj).myHashMap);
} else {
return false;
}
}
底层 map 的equals
实现忽略其内容的顺序
public boolean equals(Object o) {
if (o == this)
return true;
if (!(o instanceof Map))
return false;
Map<K,V> m = (Map<K,V>) o;
if (m.size() != size())
return false;
try {
Iterator<Entry<K,V>> i = entrySet().iterator();
while (i.hasNext()) {
Entry<K,V> e = i.next();
K key = e.getKey();
V value = e.getValue();
if (value == null) {
if (!(m.get(key)==null && m.containsKey(key)))
return false;
} else {
if (!value.equals(m.get(key)))
return false;
}
}
} catch (ClassCastException unused) {
return false;
} catch (NullPointerException unused) {
return false;
}
return true;
}
关于java - 比较 org.codehaus.jettison.json.JSONArray 而不考虑顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33427053/