SmiffyKmc SmiffyKmc - 1 year ago 387
Android Question

Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

I'm getting this exception error when using the OpenWeatherMap API. I'm just trying to get the result to be an JSONObject, but null keeps coming up.

protected void onPostExecute(String result) {

// What's coming in as result...
// Printed to the console...
// null{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear",
// "description":"clear sky","icon":"01d"}],...}

try {
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");

Log.i("Weather Info", weatherInfo);
} catch (JSONException e) {


The JSON data comes in fine but all I want is it to become a JSONObject but the null part is catching. Any Ideas why that might be happening?

Also from the site the
JSON Response
coming in is:

{"coord":{"lon":-0.13,"lat":51.51},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01d"}],.....}

How come that doesn't have null at the start?
Thank you for your help.

Answer Source

In the data you receive weather is a JSONArray.

Try this :

 String json = "{\"coord\":{\"lon\":-0.13,\"lat\":51.51},\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01d\"}],.....}";

    JSONObject jo = new JSONObject(json);
    JSONArray weather = jo.getJSONArray("weather");
    for(int i = 0;i < weather.length(); i++){
        JSONObject w = weather.getJSONObject(i);
        String main = w.getString("main");
        String description = w.getString("description");
}catch (Exception e){


As you said if the result returned by the server start with null you will have this exception org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject.

This is because this result is not a valid JSON content.

If you really receive this invalid content from the server a workaround can be to remove the null before parsing the JSON.

String crappyPrefix = "null";

    result = result.substring(crappyPrefix.length(), result.length());
JSONObject jo = new JSONObject(result);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download