我在下面有JSON响应,我想计算“ref_id”对象中字符串匹配的出现次数。但我不知道在循环数组和计算匹配时从哪里开始。我应该感谢任何帮助或建议
{
"tag": "checkthisServer",
"success": 1,
"error": 0,
"svd_ids": [
{
"ref_id": "f91e2651"
},
{
"ref_id": "f91e2651"
},
{
"ref_id": "ue87sr5d"
},
{
"ref_id": "f91e2651"
}
{
"ref_id": "ue87sr5d"
}
]
}
输出应为:
f91e2651: 3
ue87sr5d: 2
答案 0 :(得分:4)
您可以在ArrayList上使用Collections.frequency
执行此操作。首先从JSONObeject获取JSONArray,然后将其转换为ArrayList:
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");
//.....
答案 1 :(得分:0)
尝试一下:这里的filterValues是您的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;
}, {});
答案 2 :(得分:-1)
试试这个,
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;
}
}