gpt4 book ai didi

java - 将 JSONArray 转换为 HashMap 并匹配

转载 作者:行者123 更新时间:2023-11-30 06:31:14 24 4
gpt4 key购买 nike

我有一个 JSONArray,其中包含以下格式的数据:

[[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}],
[{ "Country" : "IN", "count" : 10},{ "Country" : "US", "count" : 20}]]

我想将数据放入 HashMap,如下所示:

"IN":10
"US":20
"IN":10
"US":20

基本上,我正在进行计数匹配,以确保同一类型的所有Country 具有相同的count

这是我尝试过的,JSONArray 存储为 myArray :

Map<String, Integer> cargo = new HashMap<>();
for (int j = 0; j < myArray.length(); j++) {
String country = myArray.getJSONObject(j).getString("country");
Integer count = myArray.getJSONObject(j).getInt("count");
cargo.put(country, count);
}

但我收到 JSONArray[0] is not a JSONObject 错误。

谢谢

编辑:这帮助我将其绘制到 map 上。

`

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("country");
Integer count = myArray.getJSONArray(j).getJSONObject(k).getInt("count");
cargo.put(country, count);
}

`

最佳答案

您的 JSONArray[0] 等于

[{“国家”:“IN”,“计数”:10},{“国家”:“美国”,“计数”:20}]

所以实际上不是一个 JSONObject,您需要在 for 中执行 for,以迭代每个对象。

<小时/>
for (int j = 0; j < myArray.length(); j++) {
for (int k = 0; k < myArray[j].length(); k++) {
String country = myArray[j].getJSONObject(k).getString("country");
Integer count = myArray[j].getJSONObject(k).getInt("count");
cargo.put(country, count);
}
}

关于java - 将 JSONArray 转换为 HashMap 并匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46072442/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com