tokis
tokis

Reputation: 125

Android parse json force stopped

I am parsing a json url: http://www.json-generator.com/api/json/get/bQmwsOmYeq?indent=2 but I failed to make it happen. I am getting an error. What's wrong with this code?

public void parseJsonResponse(String result) {
    Log.i(TAG, result);
    pageCount++;
    try {
        JSONObject json = new JSONObject(result);
        JSONArray jArray = json.getJSONArray("name");
        for (int i = 0; i < jArray.length(); i++) {

            JSONObject jObject = jArray.getJSONObject(i);
            CountryInfor country = new CountryInfor();
            country.setId(jObject.getString("id"));
            country.setName(jObject.getString("name"));
            countries.add(country);
        }

        adapter.notifyDataSetChanged();
        if (dialog != null) {
            dialog.dismiss();
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

Upvotes: 0

Views: 45

Answers (2)

ELITE
ELITE

Reputation: 5940

Replace

JSONObject json = new JSONObject(result);
JSONArray jArray = json.getJSONArray("name");

these two lines by

JSONArray jArray = new JSONArray(result);

Also change

country.setId(jObject.getString("id"));

by

country.setId(jObject.getInt("id") + "");

Because id is of type int not a String.

And it will work fine.

You are getting response like

[
    {
        "id": ​1,
        "name": "Vietnam"
    },
    {
        "id": ​2,
        "name": "China"
    },
    {
        "id": ​3,
        "name": "USA"
    },
    {
        "id": ​4,
        "name": "England"
    },
    {
        "id": ​10,
        "name": "Russia"
    }
]

So the response is JSONArray and not JSONObject.

Hope it'll help.

Edit

@Override
protected String doInBackground(Void... params) {

    // call load JSON from url method
    if(loadJSON(this.url) != null) {
        return loadJSON(this.url).toString();
    }
    Log.d("LoadJSONFromUrl", "Failed to get JSONObject.");
    return null;
}

You are getting JSONObject null, so the error is.

- You should know what is NullPointerException

Upvotes: 1

Viral Patel
Viral Patel

Reputation: 33398

the issue is with this line

JSONArray jArray = json.getJSONArray("name");

There is no array with name name. it is failing here. Correct this part to obtain the array properly. Rest looks fine.

Upvotes: 0

Related Questions