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

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@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是:

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

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


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

试试看:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 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内容。

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

1
2
3
4
5
6
String crappyPrefix ="null";

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


尝试一下(为我工作)..我遇到了同样的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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;
        }

有时候问题是您的响应为null,但是您希望使用JSONObject。
最好在服务器端解决该问题。如果您无法编辑服务器端代码,则此问题和该问题可能很有用


尝试一下,

1
2
3
4
5
6
7
8
9
10
11
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();
        }

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

这就是您的JSON数据所发生的事情,您通过字符串获取的数据运行良好,但是当您将其作为JSON对象放置时,它会返回异常

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

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

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

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


  • 该错误表示您的JSON无效概率

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

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

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

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

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

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

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    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类:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    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 +"\
    ");
            }

            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方法。