在开始之前,这是我的 JSON:(结构是刚性的,无法更改)
[
{"_id":{"country":"au", "industry":"foo"}, "value":{"count":2}},
{"_id":{"country":"au", "industry":"bar"}, "value":{"count":1}},
{"_id":{"country":"be", "industry":"baz"}, "value":{"count":2}},
..
]
我不能有重复的国家/地区名称和行业名称。我有一个数组,要填充值
数组[au][foo] = 2
数组[au][bar] = 1
数组[be][baz] = 2
JSON 中的值未排序,并且所有国家/地区可能不具有相同的行业。
我该如何去做呢?这是我当前的代码:
for (int i = 0; i < jsonArray.size(); i++) {
JSONObject jsonValue = jsonArray.get(i).isObject();
JSONObject _id = jsonValue.get("_id").isObject();
JSONObject value = jsonValue.get("value").isObject();
String country = _id.get("country").isString().toString();
setCountry.add(country);
String industry = _id.get("industry").isString().toString();
setIndustry.add(industry);
int count = Integer.parseInt(value.get("count").isNumber()
.toString());
}
我正在将国家/地区和行业添加到集合中,以删除重复项。这就是导致计数问题的原因。我不在乎它是否优雅,黑客工作也可以。
谢谢。
最佳答案
我认为您可以使用枚举来解决您的问题。在这样的枚举中定义所有已知的国家/地区名称和行业。
public enum Country {
au,
be;
int Int=this.ordinal();//just a short name for ordinal
}
和
public enum Industry {
foo,
bar,
baz;
int Int=this.ordinal();
}
现在定义一个二维 int 数组,您可以使用枚举设置值,如下所示:
int[][] value=new int[Country.values().length][Industry.values().length];
value[Country.au.Int][Industry.bar.Int]=2;
//Read from JSON
value[Country.valueOf("au").Int][Industry.valueOf("bar").Int]=2;
如果您使用枚举,则可以将此代码添加到当前 for 循环的末尾:
value[Country.valueOf(country).Int][Industry.valueOf(industry).Int]=count;
另一种选择是避免使用数组并使用 Map 来代替:
Map<Country,Map<Industry,Integer>> m=new HashMap<Country,Map<Industry,Integer>>();
或者简单地不使用枚举:
Map<String,Map<String,Integer>> m=new HashMap<String,Map<String,Integer>>();
map 的问题在于,从其中添加和检索值有点棘手,但您可以编写通用方法来完成这项工作。
更新:
向内部映射添加值:
String[][] countryAndIndustry= {{"au","foo"},{"au","bar"},{"be","baz"}};
Integer[] count= {2,1,2};
HashMap<String,HashMap<String,Integer>> hm=new HashMap<String, HashMap<String,Integer>>();
for(int i=0;i<count.length;i++)
{
HashMap<String,Integer> innerMap=hm.get(countryAndIndustry[i][0]);
if(innerMap==null)
{
innerMap=new HashMap<String, Integer>();
hm.put(countryAndIndustry[i][0],innerMap);
}
innerMap.put(countryAndIndustry[i][1],count[i]);
}
关于java - 使用 JSON 中的值填充数组很棘手,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3904209/