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

SmiffyKmc picture SmiffyKmc · Apr 13, 2016 · Viewed 22.4k times · Source

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.

@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(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) {
            e.printStackTrace();
        }

   }

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

Guillaume Barré picture Guillaume Barré · Apr 13, 2016

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\"}],.....}";

try{
    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";

if(result.startsWith(crappyPrefix)){
    result = result.substring(crappyPrefix.length(), result.length());
}
JSONObject jo = new JSONObject(result);