编辑:我从错误的物体上得到了花车——我的错。虽然时间戳有同样的问题 - Int 无法转换为 JSONObject
我从 openweathermap 得到了城市和国家罚款,但应用程序在浮动值上崩溃。我对 android 非常陌生,并且是我第一次使用 JSON,因此将不胜感激。我正在阅读 7 天的预测。这是我的 WeatherParser 类,它从文本视图中传递了一个城市位置:
JSONObject jObj = new JSONObject(data);
JSONObject city = jObj.getJSONObject("city");
Location loc = new Location();
loc.setCity(getString("name", city));
loc.setCountry(getString("country", city));
weather.setLocation(loc);
JSONArray jArr = jObj.getJSONArray("list");
for (int i = 0; i < jArr.length(); i++) {
JSONObject dailyForecast = jArr.getJSONObject(i);
JSONObject time = dailyForecast.getJSONObject("dt");
JSONObject temp = dailyForecast.getJSONObject("temp");
JSONObject dayTemp = temp.getJSONObject("day");
JSONObject max = temp.getJSONObject("max");
JSONObject min = temp.getJSONObject("min");
DailyForecast df = new DailyForecast();
long unixSeconds = (long) getLong("dt", time);
Date date = new Date(unixSeconds*1000L); // *1000 is to convert minutes to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.US);
String formattedDate = sdf.format(date);
df.setDay(formattedDate);
df.setTemp(getFloat("day", dayTemp));
df.setMax(getFloat("max", max));
df.setMin(getFloat("min", min));
JSONArray jAr = dailyForecast.getJSONArray("weather");
if(jAr.length() > 2) {
JSONObject desc = jAr.getJSONObject(2); //get the 3rd item
df.setDesc(getString("description", desc));
}
weeksForecast[i] = df;
}
weather.fillForecast(weeksForecast);
return weather;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
private static float getFloat(String tagName, JSONObject jObj)
throws JSONException {
return (float) jObj.getDouble(tagName);
}
private static float getLong(String tagName, JSONObject jObj)
throws JSONException {
return (long) jObj.getDouble(tagName);
}
}
10-24 19:48:03.728:D/gralloc_goldfish(954):没有检测到 GPU 仿真的仿真器。10-24 19:48:12.398: D/dalvikvm(954): GC_FOR_ALLOC 释放 163K, 9% 释放 2855K/3136K, 暂停 36ms, 总共 36ms 10-24 19:48:12.448: W/System.err(954): org.json.JSONException:java.lang.Double 类型日的值 12.74 无法转换为 JSONObject 10-24 19:48:12.448:W/System.err(954):在 org.json.JSON.typeMismatch(JSON .java:100) 10-24 19:48:12.448: W/System.err(954): 在 org.json.JSONObject.getJSONObject(JSONObject.java:577) 10-24 19:48:12.448: W/System .err(954): 在 com.meaProject.yawa.WeatherParser.getWeather(WeatherParser.java:31) 10-24 19:48:12.448: W/System.err(954): 在 com.meaProject.yawa.MainActivity$ JSONWeatherTask.doInBackground(MainActivity.java:58) 10-24 19:48:12.458: W/System.err(954): 在 com.meaProject.yawa.MainActivity$JSONWeatherTask。