我试图通过volley从openweathermap.com获取json 我有这个java代码:
public void findWeather(int latitude,int longitude){
final Info info=new Info();
url="http://api.openweathermap.org/data/2.5/forecast?lat="+latitude+"&lon="+longitude+"&appid=9a40ef2a4c35689b29978690445e03e0&units=metric";
final JsonObjectRequest objectRequest=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray=response.getJSONArray("list");
JSONObject jsonObjectMain=jsonArray.getJSONObject(0).getJSONObject("main");
JSONObject jsonObjectWeather=jsonArray.getJSONArray(2).getJSONObject(0);
JSONObject jsonObjectWind=jsonArray.getJSONObject(5);
String date=jsonArray.getString(6);
info.setTemp(jsonObjectMain.getString("temp"));
info.setDescription(jsonObjectWeather.getString("description"));
info.setWind(jsonObjectWind.getString("speed"));
info.setHumidity(jsonObjectMain.getString("humidity"));
info.setPresure(jsonObjectMain.getString("pressure"));
info.setDate(date);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}......}
});
RequestQueue queue=Volley.newRequestQueue(this);
queue.add(objectRequest);
}
,错误如下
org.json.JSONException: Value {"dt":1520380800,"main":{"temp":6.82,"temp_min":6.82,"temp_max":7.6,"pressure":1010.5,"sea_level":1030.48,"grnd_level":1010.5,"humidity":74,"temp_kf":-0.77},"weather":[{"id":801,"main":"Clouds","description":"few clouds","icon":"02n"}],"clouds":{"all":24},"wind":{"speed":1.26,"deg":161.501},"sys":{"pod":"n"},"dt_txt":"2018-03-07 00:00:00"} at 2 of type org.json.JSONObject cannot be converted to JSONArray
我有来自邮政编码的openweathermap.org的json代码如下:
{
"cod": "200", "message": 0.0031,
"cnt": 40,
"list": [
{
"dt": 1520337600,
"main": {
"temp": 9.15,
"temp_min": 9.15,
"temp_max": 9.64,
"pressure": 1032.25,
"sea_level": 1041.73,
"grnd_level": 1032.25,
"humidity": 100,
"temp_kf": -0.5
},
"weather": [
{
"id": 802,
"main": "Clouds",
"description": "scattered clouds",
"icon": "03n"
}
],
"clouds": {
"all": 32
},
"wind": {
"speed": 9.92,
"deg": 55.5024
},
"rain": {},
"sys": {
"pod": "n"
},
"dt_txt": "2018-03-06 12:00:00"
}, ......
问题究竟在哪里? 我怎么解决这个问题 ?? 请帮帮我,非常感谢..
答案 0 :(得分:1)
你的问题是
JSONObject jsonObjectWeather=jsonArray.getJSONArray(2).getJSONObject(0);
jsonArray是'list'的内容,所以如果你想要天气,你应该这样做:
jsonArray.getJSONObject(0).getJSONObject("weather").getJSONArray(0).getJSONObject(0);
这样的事情。 但手动解析JSON是一个痛苦的问题。
使用Gson,它会更容易。
您定义对象结构,然后执行
Gson gson = new Gson();
YourRootClass res = gson.fromJson(json, YourRootClass.class);
*魔法*
答案 1 :(得分:0)
JSONArray jsonArray = response.getJSONArray(&#34; list&#34;);
JSONObject jsonObjectMain=jsonArray.getJSONObject(0).getJSONArray("weather")