首页 > 解决方案 > java.lang.String 类型的值无法转换为 JSONObject(openweather API)

问题描述

这是我的代码:

public class DownloadTask extends AsyncTask<String,Void,String> {

    @Override
    protected String doInBackground(String... urls) {
        String result = "";
        URL url;
        HttpURLConnection urlConnection = null;

        try {

            url = new URL(urls[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();

            while (data != -1) {
                char current = (char) data;
                result += current;
                data = reader.read();
            }

            return result;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);

        try {
            JSONObject jsonObject = new JSONObject(s);

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

            Log.i("Weather content", weatherInfo);

            JSONArray arr = new JSONArray(weatherInfo);

            for (int i=0; i < arr.length(); i++) {
                JSONObject jsonPart = arr.getJSONObject(i);

                Log.i("main",jsonPart.getString("main"));
                Log.i("description",jsonPart.getString("description"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    DownloadTask task = new DownloadTask();
    task.execute("http://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b1b15e88fa797225412429c1c50c122a1");
}

日志猫射击

出现此错误。它说 java.lang.String 类型的值不能转换为 JSONObject。但是我看到 Udemy 的一位讲师使用了相同的代码。我不明白为什么它对我不起作用。我该如何解决这个问题?我需要对我的代码进行哪些更改?

标签: javaandroidjson

解决方案


weatherInfo 必须是 JSONArray,而不是 String 然后获取索引为 0 的 String

JSONArray jsonArray = jsonObject.getJSONArray("天气"); JSONObject jsonWeather = jsonArray.getJSONObject(0);


推荐阅读