org.json.JSONObject$1 类型的值 null 无法转换为 JSONObject

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

我在使用 OpenWeatherMap API 时收到此异常错误。我只是想让 result 成为一个 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,但空部分正在捕获。知道为什么会这样吗?

同样来自网站的 JSON Response 是:

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

为什么开头没有null? 感谢您的帮助。

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

试试这个:

 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 cannot be converted to JSONObject

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

如果您确实从服务器收到此无效内容,解决方法是在解析 JSON.

之前删除 null
String crappyPrefix = "null";

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

错误意味着你的JSON无效可能

您可以测试您的 JSON 格式 here

但是你的代码中的问题是你试图在这里使用 getString()

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

虽然天气实际上是JSON数组,但如果你想把它作为字符串使用

String weatherInfo = jsonObject.getJSONArray("weather").toString();

试试这个,

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

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

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

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

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;
        }

有时问题是您的响应为空,但您期望的是 JSONObject。 最好在服务器中解决它 side.if 你不能编辑服务器端代码,this question and this one 可能有用

成员变量默认初始化, 在 String 的情况下,它被初始化为 null IE。写作 String xyz; 等价于 String xyz=null; 当我们将这个空字符串连接到另一个字符串时,java 编译器将空值设为一个字符串 IE。 xyz=xyz+"abc"; //would result as nullabc

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

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

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

  2. 或者您可以删除字符串开头的空值,如

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