java - 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 的一位讲师使用了相同的代码。我不明白为什么它对我不起作用。我该如何解决这个问题?我需要对我的代码进行哪些更改?
解决方案
weatherInfo 必须是 JSONArray,而不是 String 然后获取索引为 0 的 String
JSONArray jsonArray = jsonObject.getJSONArray("天气"); JSONObject jsonWeather = jsonArray.getJSONObject(0);
推荐阅读
- android - Kotlin,Android Studio 中的自定义 .svg 谷歌地图标记
- python - 一次运行 10 个循环
- twitter - Twitter 代码:89 令牌无效或过期
- ocaml - 在沙丘冲突中运行 utop:extlib 和 base64
- node.js - 初始 React npm start 构建失败
- mysql - SQL 查询中的 IS NULL 和 IS NOT NULL 不起作用
- c# - VB6 无法使用从字节数组动态加载程序集的 C# 库
- javascript - JavaScript中的浮点数精度
- ajax - 页面加载时的无缝视频背景
- matlab - 使用 fmincon 内点算法的最优容差