【发布时间】:2017-09-06 20:07:41
【问题描述】:
我有一个 JSONArray 格式:
[[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}], [{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}], [{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]]
我想比较上述案例中的各个字段
因为{ "Country" : "IN", "count" : 10} 等于{ "Country" : "IN", "count" : 10} 和{ "Country" : "IN", "count" : 10} 和{ "Country" : "US", "count" : 20} 等于{ "Country" : "US", "count" : 20} 和{ "Country" : "US", "count" : 20},我应该得到一个匹配结果。
但是对于下面这样的情况,我应该得到一个不匹配的结果,因为 count 不匹配。
[[{ "Country" : "IN", "count" : 45},{ "Country" : "US", "count" : 60}],
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}],
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]]
我能够将数据放入 HashMap。但是我找不到方法,如何比较。
myArray 包含上述 JSONArray。
int length = myArray.getJSONArray(0).length();
Map<String, Integer> cargo = new HashMap<>();
for (int j = 0; j < myArray.length(); j++) {
for (int k = 0; k < myArray.getJSONArray(j).length(); k++) {
String country = myArray.getJSONArray(j).getJSONObject(k).getString(DataConstants.COUNTRY);
Integer count = myArray.getJSONArray(j).getJSONObject(k).getInt(DataConstants.COUNT);
cargo.put(country, count);
}
}
if (cargo.size() == length) {
System.out.println("Data Matched !!");
return true;
}
else
System.out.println("Data Not Matched !!");
return false;
谢谢,
【问题讨论】:
-
您需要将 JSON 数组转换为 java 对象并覆盖 equals 和 hashcode 方法。
-
@alayor 有没有一些链接/代码你可以指点我 overeeride equals 和 hashcode 方法?
-
@Aya:在 alayor 的评论中有四个明显的关键词。在 Google(或 Stack Overflow)的搜索字段中输入“Java”、“override”、“equals”和“hashCode”会比要求我们为您做更容易和更快。
-
@KevinJ.Chase 我知道你是对的,但你没有义务回应。这完全取决于你。对不起,如果我听起来很苛刻。