11

使用 OpenWeatherMap API 时出现此异常错误。我只是想让结果成为 JSONObject,但null不断出现。

@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();
        }

   }

JSON 数据很好,但我只想让它成为 JSONObject,但 null 部分正在捕获。任何想法为什么会发生这种情况?

同样从该网站JSON Response进来的是:

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

为什么一开始就没有 null ?谢谢您的帮助。

4

7 回答 7

10

在您收到的数据中,天气是一个 JSONArray。

尝试这个 :

 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){

}

如您所说,如果服务器返回的结果以您开头,null则会出现此异常org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONObject

这是因为此结果不是有效的 JSON 内容。

如果您确实从服务器收到此无效内容,解决方法可以是null在解析 JSON 之前删除。

String crappyPrefix = "null";

if(result.startsWith(crappyPrefix)){
    result = result.substring(crappyPrefix.length(), result.length());
}
JSONObject jo = new JSONObject(result);
于 2016-04-13T13:37:36.130 回答
5

试试这个(对我有用)..我遇到了同样的问题

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;
        }
于 2016-09-17T17:28:08.730 回答
4

有时问题是您的响应为空,但您期望 JSONObject。最好在服务器端解决它。如果你不能编辑服务器端代码,这个问题这个问题可能会有用

于 2018-12-13T06:43:37.800 回答
2

尝试这个,

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();
        }
于 2016-04-13T13:38:09.790 回答
0

该错误意味着您的 JSON 可能无效

您可以在此处测试您的 JSON 格式。

但是您的代码中的问题是您尝试在此处使用 getString()

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

虽然天气实际上是 JSONArray,但如果您希望它作为字符串使用

String weatherInfo = jsonObject.getJSONArray("weather").toString();
于 2016-04-13T13:37:59.600 回答
0

成员变量默认初始化,如果是 String 则初始化为null ie。写作String xyz;是等价的String xyz=null; ,当我们将这个空字符串连接到另一个字符串时,java编译器将空值变成一个字符串,即。xyz=xyz+"abc"; //would result as nullabc

这就是您的 JSON 数据所发生的情况,您作为字符串获得的数据工作正常,但是当您将其作为 JSON 对象放置时,它会返回异常

"Value null of type org.json.JSONObject$1 cannot be converted to JSONObject"因为它将其视为空值。

  1. 最好将字符串初始化为空字符串,即。 String xyz="";

  2. 或者您可以将字符串开头的 null 删除为

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

于 2020-09-08T06:58:33.983 回答
-1

试试下面的代码,它对我有用。

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 类:

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 是我的 Getter-Setter 方法。

于 2016-04-13T13:44:12.813 回答