Reputation: 134
I have the JSON response below and I want to count the occurrence of string matches in the "ref_id" objects. But I have no idea where to start when looping through the array and counting the matches. Any help or recommendation where I should start would be appreciated
{
"tag": "checkthisServer",
"success": 1,
"error": 0,
"svd_ids": [
{
"ref_id": "f91e2651"
},
{
"ref_id": "f91e2651"
},
{
"ref_id": "ue87sr5d"
},
{
"ref_id": "f91e2651"
}
{
"ref_id": "ue87sr5d"
}
]
}
Output should be:
f91e2651: 3
ue87sr5d: 2
Upvotes: 1
Views: 5860
Reputation: 1
Try This : Here filterValues is your JSON
filterValues = filterValues.reduce((newObj, obj) => {
let value = 1;
if(newObj[obj[ref_id]]) {
value = value + 1;
newObj[obj[ref_id]] = obj[ref_id] + ' (' + value + ')';
} else {
newObj[obj[ref_id]] = obj[ref_id] + ' (' + value + ')';
}
return newObj;
}, {});
Upvotes: 0
Reputation: 977
Try this,
JSONArray responseArray = jsonObject.getJSONArray("svd_ids");
int countFirst = 0, countSecond = 0;
for (int i = 0; i < responseArray.length(); i++) {
JSONObject obj = responseArray.getJSONObject(i);
if (obj.optString("ref_id").equals("f91e2651") {
countFirst = countFirst + 1;
}
if (obj.optString("ref_id").equals("ue87sr5d") {
countSecond = countSecond + 1;
}
}
Upvotes: -1
Reputation: 132982
You can do it using Collections.frequency
on ArrayList. so first get JSONArray from JSONObeject then convert it to ArrayList as:
JSONObject mainobj=new JSONObject("your json string");
// get svd_ids JSONArray
JSONArray json_array=mainobj.getJSONArray("svd_ids");
// get ArrayList from JSONArray
ArrayList<String> listsvd_ids = new ArrayList<String>();
for (int i=0;i<json_array.length();i++){
listsvd_ids.add(json_array.get(i).toString());
}
// occurrence of f91e2651
int occur_f91e2651 = Collections.frequency(listsvd_ids, "f91e2651");
// occurrence of ue87sr5d
int occur_ue87sr5d = Collections.frequency(listsvd_ids, "ue87sr5d");
//.....
Upvotes: 6