Vidar
Vidar

Reputation: 41

Iterating through JSONObjects

I have tried several of the examples listed and none of them seem to work for some reason so I am posting a new question.

I have a JSON string coming to me however it is all objects (it is not formatted in an array). I need to parse out the Team names from this. I know I need to iterate over them as they are the keys and then store the objects in a new array.

Here is the JSON (a sample of it)

{"query":{"printrequests":[{"label":"","typeid":"_wpg","mode":2,"format":false}],"results":{"Team:Kubbchucks":{"printouts":[],"fulltext":"Team:Kubbchucks","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks","namespace":822,"exists":true},"Team:Kubbchucks IDP":{"printouts":[],"fulltext":"Team:Kubbchucks IDP","fullurl":"http://wiki.planetkubb.com/wiki/Team:Kubbchucks_IDP","namespace":822,"exists":true}},"serializer":"SMW\Serializers\QueryResultSerializer","version":0.5,"meta":{"hash":"8407a177d701d746edc3066a012c17d2","count":2,"offset":0}}}

What I have so far to dig down to that level of the JSON (data is the string above)

JSONObject parsing = new JSONObject(data);
JSONObject query = parsing.getJSONObject("query");
JSONObject results = query.getJSONObject("results");

This allows me to manually check for a team using :

JSONObject teamone = results.getJSONObject("Team:Kubbchucks");

This is of course not ideal. The full JSON file has almost 3000 entries and I do not know what those entries all are. I need to iterate over the results object to get the keys that start with "Team:"

I've tried a few different iterator samples but none seem to be working for me and it is starting to really frustrate me. Believe me, I've tried many things before asking the question. Any help is appreciated.

Upvotes: 0

Views: 60

Answers (1)

Ayoub
Ayoub

Reputation: 341

I had a similar problem some time ago. You can do like this:

JSONObject results = query.getJSONObject("results");
Iterator<String> iterator = results.keys();
while (iterator.hasNext()) {
    JSONObject team = results.getJSONObject(iterator.next());
    // do stuff
}

Upvotes: 1

Related Questions