14

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.

Shvet
  • 1,159
  • 1
  • 18
  • 30
SmiffyKmc
  • 801
  • 1
  • 16
  • 34

8 Answers8

10

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);
Guillaume Barré
  • 4,168
  • 2
  • 27
  • 50
  • Thanks for the reply. I'm still getting the error _Value null of type org.json.JSONObject$1 cannot be converted to JSONObject_ . It just doesn't seem to want to take the JSON data coming in. The site I'm getting it from doesn't have null at the very start, but when I get it in the _result_ it does. Does that matter? – SmiffyKmc Apr 13 '16 at 13:44
  • That's really interesting actually! Thanks for explaining that :). But I don't want to use a hard coded String as I'm trying to learn how to do it from an API. The newest Update looks really clever. I keep forgetting about string manipulation. I'll give that a go! Thank you. – SmiffyKmc Apr 13 '16 at 14:01
  • @Nirekin for handling null object first i have to remove null from that result...no other way to handle that – Manish Nov 17 '16 at 04:47
5

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;
        }
Amit Kumar
  • 583
  • 5
  • 16
5

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

masoud jafari
  • 522
  • 9
  • 14
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. [how to answer](https://stackoverflow.com/help/how-to-answer) – Agilanbu Dec 13 '18 at 07:02
2

try this,

JSONObject jsonObject = new JSONObject(result);
        try {
            JSONArray jsonArray = jsonObject.getJSONArray("weather");

            for(int i=0;i<jsonArray.length();i++){
                JSONObject object=jsonArray.getJSONObject(i);
                String main =object.getString("main");
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
Pradeep Gupta
  • 1,770
  • 1
  • 9
  • 23
1

The best solution is use of .isNull

if(result.has('objectName') && !result.isNull('objectName'))
Rohit Lalwani
  • 529
  • 7
  • 14
0

The error means that your JSON is not valid probabaly

You can test your JSON format here.

But the problem in your code is that you are trying to use getString() here

String weatherInfo = jsonObject.getString("weather");

While weather is actually JSONArray, if you want it as string use

String weatherInfo = jsonObject.getJSONArray("weather").toString();
Slobodan Antonijević
  • 2,533
  • 2
  • 17
  • 27
0

Member Variables are initialized by default, in case of String it gets initialized as null ie. writing String xyz; is equivalent String xyz=null; and when we concatenate this null string to another string, java compiler make null value a string ie. xyz=xyz+"abc"; //would result as nullabc

That is what's happening to your JSON data, the data you're getting as the string is working fine but as you put it as a JSON object it returns the exception

"Value null of type org.json.JSONObject$1 cannot be converted to JSONObject" because it treats that as a null value.

  1. The best thing to do initialize string as an empty string ie. String xyz="";

  2. Or you may either remove that null at the beginning of the string as

    if(result.startsWith("null")){ result = result.substring("null".length(), result.length()); } JSONObject json = new JSONObject(result);

Harshit Jain
  • 885
  • 11
  • 15
-1

try this below code , it's working for me.

JSONParser jParser = new JSONParser();
JSONObject weatherUrlObject =jParser.getJSONFromUrl(weatherUrl);
 try {
        JSONArray weather = weatherUrlObject.getJSONArray("weather");
        WeatherNow.setWeather_id(weather.getJSONObject(0).getString("id").toString());
        WeatherNow.setWeather_main(weather.getJSONObject(0).getString("main").toString());
        WeatherNow.setWeather_description(weather.getJSONObject(0).getString("description").toString());
        WeatherNow.setWeather_icon(weather.getJSONObject(0).getString("icon").toString());
    } catch (Exception e) {
                    e.printStackTrace();
                }

JSONPaser Class:

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient

        DefaultHttpClient httpClient = new DefaultHttpClient();

        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();          

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }

        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}
}

WeatherNow is my Getter-Setter method .

Nirmal Shethwala
  • 268
  • 1
  • 15
  • What is `JSONParser` and `WeatherNow`? dont post anything without any explanation. – Shvet Apr 13 '16 at 13:46
  • Thanks for the fast reply. I'm trying to get the _result_ coming into the method to become the JSONObject first but thats where the issue is coming. – SmiffyKmc Apr 13 '16 at 13:49
  • String weatherInfo = jsonObject.getString("weather"); replace : JSONArray weather = jsonObject.getJSONArray("weather"); – Nirmal Shethwala Apr 13 '16 at 13:54