下面是我的代码:
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.I的讲师身上工作,我不明白为什么它不能在我身上工作。我该如何解决这个问题?我需要在我的代码中进行哪些更改?
发布于 2018-12-17 03:51:04
weatherInfo必须为JSONArray,而不是String,然后获取索引为0的字符串
JSONArray jsonArray =jsonObject.getJSONArray(“天气”);JSONObject jsonWeather = jsonArray.getJSONObject(0);
https://stackoverflow.com/questions/53805680
复制相似问题