Value null of type org.json.JSONObject$1 cannot be converted to JSONObject
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);
Try This (worked for me).. I was having same problem
public class DownloadData extends AsyncTask<String , Void, String >{
HttpURLConnection httpURLConnection =null;
URL url;
String resultString=""; <------- instead of setting it to null
@Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while(data != -1){
char ch = (char) data;
resultString += ch;
data = isr.read();
}
return resultString;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
some times the problem is your response is null, but you expect a JSONObject. its bettter to resolve it in server side.if you can not edit server side code, this question and this one may be useful