Reputation: 14585
I;m trying to parse a json string which I receive from web server as a response, but I have a strange issue. In my json I have a few JSONObjects
, which I never know what will be their names and I should cycle them depending on how much keys
it has. But the problem is with the code I'm using it's getting the same value everytime even when I know that there is other values too.
Here is the cod which I'm using :
JSONObject json = (JSONObject) new JSONTokener(jsonBuffer).nextValue();
JSONObject country = json.getJSONObject(String.valueOf(json.keys().next()));
Iterator<Object> keys = json.keys();
while (keys.hasNext()) {
String countryName = country.getString("country_name");
Log.e("","country_name: "+countryName);
String data = country.getString("data");
Log.e("","data : "+data);
}
and here is what my json looks like :
"AZ": {
"country_name": "Azerbaijan",
"data": {
"181261": {
"time_published": "2012-04-04 15:55:29",
"title": "Azerbaijan, Turkey not to change stakes in TANAP",
"body": null
},
"181260": {
"time_published": "2012-04-04 15:53:10",
"title": "SOCAR mulls acquisition of Swiss refinery",
},
"181061": {
"time_published": "2012-04-03 05:53:00",
"title": "Azerbaijan, Lithuania mull LNG terminal investment",
},
// and so on....
}
}, // and it keeps going on
Any ideas how my jsonParser should looks like?
Upvotes: 1
Views: 1001
Reputation: 568
It doen't loop over country names because the code just checks if it has next and never get to the next one. but also the rest of the code seems not working too. you need to get the json.keys() first to a local variable, and then iterate over it.
Upvotes: 1
Reputation: 816840
I'm not very familiar with Android and Java, but I assume it should be:
// parse JSON
JSONObject json = (JSONObject) new JSONTokener(jsonBuffer).nextValue();
// get all keys (they are probably strings)
Iterator<String> keys = json.keys();
// as long as there are more keys
while (keys.hasNext()) {
// get the object corresponding to the next key
JSONObject country = json.getJSONObject(keys.next());
String countryName = country.getString("country_name");
Log.e("","country_name: "+countryName);
String data = country.getString("data");
Log.e("","data : "+data);
}
From my comments:
It looks to me that you have an endless while
loop, it actually never gets out to assign a new value to country
.
You have to iterate over all keys, get the country object for the key, and then access it's values.
Currently you are getting the first country element, get the keys and just check whether the iterator contains keys. But you are not advancing the iterator.
Upvotes: 2
Reputation: 328745
Shouldn't your code be:
Iterator<Object> keys = json.keys();
while (keys.hasNext()) {
JSONObject country = json.getJSONObject(String.valueOf(keys.next()));
//etc.
}
Upvotes: 1