1

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.

1
  • Are you sure that you aren't getting an exception for every item because you are trying to coerce a String to an int? Commented Oct 3, 2015 at 8:45

2 Answers 2

4

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

1 Comment

Please refer this androidhive.info/2012/01/android-json-parsing-tutorial to know about difference between JsonArray and JsonObject
2

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.

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.