在android中处理网络请求响应



我创建了一个android应用程序,使用Volleyneneneba API处理网络请求。我已经设法从服务器获得了响应,但我无法循环处理结果JSON的不同对象,当我将数据添加到Listview时,它只会给我应用程序的包名,并在末尾添加一个数字。

这是我想要处理的回应

{
"list": [
{
"dt": 1637172000,
"main": {
"temp": 301.79,
"feels_like": 300.34,
"temp_min": 298.24,
"temp_max": 301.79,
"pressure": 1008,
"sea_level": 1008,
"grnd_level": 854,
"humidity": 20,
"temp_kf": 3.55
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"clouds": {
"all": 7
},
"wind": {
"speed": 3.77,
"deg": 46,
"gust": 8.98
},
"visibility": 10000,
"pop": 0,
"sys": {
"pod": "n"
},
"dt_txt": "2021-11-17 18:00:00"
}
]
}

对象模型及其字段

public class WeatherReportModel {
private int dt;
private JSONObject main;
private JSONArray weather;
private JSONObject clouds;
private JSONObject wind;
private int visibility;
private double pop;
private JSONObject sys;
private String dt_txt;
public WeatherReportModel(
int dt, 
JSONObject main, 
JSONArray weather, 
JSONObject clouds, 
JSONObject wind, 
int visibility, 
double pop, 
JSONObject sys, 
String dt_txt) {
this.dt = dt;
this.main = main;
this.weather = weather;
this.clouds = clouds;
this.wind = wind;
this.visibility = visibility;
this.pop = pop;
this.sys = sys;
this.dt_txt = dt_txt;
}
}

这是一个回调函数,用于获取响应并添加到Model的对象中

public void getWeather(VolleyResponseListener forecast) {
List<WeatherReportModel> weatherReportModels = new ArrayList<>();
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray weather_list = response.getJSONArray("list");
// get the first item

for (int i = 0; i < weather_list.length(); i++) {
WeatherReportModel one_day_weather = new WeatherReportModel();
JSONObject first_day_from_api = (JSONObject) weather_list.get(i);
one_day_weather.setDt(first_day_from_api.getInt("dt"));
one_day_weather.setMain(first_day_from_api.getJSONObject("main"));
one_day_weather.setWeather(first_day_from_api.getJSONArray("weather"));
one_day_weather.setClouds(first_day_from_api.getJSONObject("clouds"));
one_day_weather.setWind(first_day_from_api.getJSONObject("wind"));
one_day_weather.setVisibility(first_day_from_api.getInt("visibility"));
one_day_weather.setPop(first_day_from_api.getLong("pop"));
one_day_weather.setSys(first_day_from_api.getJSONObject("sys"));
one_day_weather.setDt_txt(first_day_from_api.getString("dt_txt"));
weatherReportModels.add(one_day_weather);
}
forecast.onResponse(weatherReportModels);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
//get the property call consolidated weather
MySingleton.getInstance(context).addToRequestQueue(request);
}

通常,像这样使用ArrayAdapter时,会尝试使用toString((函数来获取值并显示它WeatherReportModel,然后重试。

最新更新