Before I begin, this is my JSON: (The structure is rigid, and cant be changed)
[
{"_id":{"country":"au", "industry":"foo"}, "value":{"count":2}},
{"_id":{"country":"au", "industry":"bar"}, "value":{"count":1}},
{"_id":{"country":"be", "industry":"baz"}, "value":{"count":2}},
..
]
I cant have duplicate country names, and industry names. I have an array that is to be filled with values as
array[au][foo] = 2
array[au][bar] = 1
array[be][baz] = 2
the values are unsorted in the JSON, and all countries might not have the same industries.
How do i go about doing that? This is my current code:
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());
}
Im adding the country and industry to a set, to remove the duplicates. thats what causing the issue about the count. I dont care for it to be elegant, a hackjob will also do.
Thanks.
I think you can make use of enum’s for your problem.Define all the known country names and Industry in an enum like this.
and
Now define a 2d int array and you can set the value’s using the enum’s like this :
You can add this code to the end of your current for loop if your using enum’s:
Another option is to avoid an array and use Map instead:
or simply without enums :
The problem with map is that it is a bit tricky to add and retrieve value’s from it but you can write common method’s to do this job.
UPDATE:
Adding values to inner map: