Reputation: 4808
How can I parse an json array in android looking like:
["BHUBANESWAR","BANGALORE CANT","BRAHMAPUR","VISAKHAPATNAM",
"VIJAYAWADA ROAD","ASOKHAR","CHAURAKHERI","BANIHAL","SADURA","ANANTNAG",
"PANJGAM","AWANTIPURA","KAKAPORA","PAMPORE"]
What I am trying is:
try {
JSONObject json = new JSONObject(s);
JSONArray jsonArray = json.names();
for ( int i = 0 ; i < jsonArray.length();i++)
{
Toast.makeText(getApplicationContext(),jsonArray.getInt(i),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
But I am not getting any output.
Upvotes: 1
Views: 1007
Reputation: 7082
uday's answer is right, let me offer some more detailed explanation o that.
JSON offers two basic data structures: Object and Array.
Object is formatted like this:
"name":{value(s)}
Value(s) may be another Object, an Array or just some data.
Array, on the other hand, is formatted like this:
[{value}, {value}, {value}...]
Again, value may be an Object, another array or, as in your example, a simple piece of data.
Your error happened because you assumed that the data you receive is an object with an array inside. However, it was actually an anonymous array, which means you can not parse into an JSONObject
first, you need to use JSONArray
right from the beginning.
So this is an anonymous array:
["BHUBANESWAR","BANGALORE CANT","BRAHMAPUR","VISAKHAPATNAM",
"VIJAYAWADA ROAD","ASOKHAR","CHAURAKHERI","BANIHAL","SADURA","ANANTNAG",
"PANJGAM","AWANTIPURA","KAKAPORA","PAMPORE"]
And if it was an object (called, for example, myArray), it would look like this:
"myArray":["BHUBANESWAR","BANGALORE CANT","BRAHMAPUR","VISAKHAPATNAM",
"VIJAYAWADA ROAD","ASOKHAR","CHAURAKHERI","BANIHAL","SADURA","ANANTNAG",
"PANJGAM","AWANTIPURA","KAKAPORA","PAMPORE"]
The difference is very little (just the "myArray":
part) but it must nevertheless be parsed in the right way, or else the parser will fail.
Upvotes: 2
Reputation: 1368
try this...
try {
JSONArray jsonArray = new JSONArray(s);
for ( int i = 0 ; i < jsonArray.length();i++) {
Toast.makeText(getApplicationContext(),jsonArray.getString(i),Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
Upvotes: 4