1

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
1
  • 2
    Look up JSONArray. Loop through and put initial result in Hashmap. If ref_id is already in Hahsmap then increment value. Commented Feb 24, 2014 at 5:00

3 Answers 3

6

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");
//.....
Sign up to request clarification or add additional context in comments.

Comments

0

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;
}, {});  

Comments

-1

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;
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.