大家好,我已经成功地进行了改造,从其余API获取数据并将其打印到日志中。但是,当我尝试将此响应捕获到数组列表中时,出现了一条错误消息:“无法推断参数(无法解析构造函数)。此错误显示在数组列表括号<>
中// Executes the network request on a background thread
try {
Response response = getWeather(locationCode, apiKey).execute();
if (cancelRequest) {
return;
}
if (response.code() == 200) {
// Weather weather = response.body().getWeather();
Log.d(TAG, "onResponse: " + response.body().toString());
List<Weather> list = new ArrayList<>(((Weather)response.body()));
//mWeather.postValue(response);
GSON回复
{
"coord": {
"lon": -5.93,
"lat": 54.58
},
"weather": [
{
"id": 804,
"main": "Clouds",
"description": "overcast clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 291.56,
"feels_like": 286.36,
"temp_min": 291.15,
"temp_max": 292.15,
"pressure": 1024,
"humidity": 45
},
如果有人可以帮助我成为根本原因,将不胜感激。
我认为您创建的POJO类可能不合适,因为您尚未共享POJO类,请在代码中尝试下面的POJO类,看看错误是否仍然存在。
public class Weather {
private coordinate coord;
private ArrayList<weatherinfo> weather;
private String base;
private maininfo main;
public coordinate getCoord() {
return coord;
}
public ArrayList<weatherinfo> getWeather() {
return weather;
}
public String getBase() {
return base;
}
public maininfo getMain() {
return main;
}
public static class coordinate{
String lon,lat;
public String getLon() {
return lon;
}
public String getLat() {
return lat;
}
}
public static class weatherinfo{
String id,main,description,icon;
public String getId() {
return id;
}
public String getMain() {
return main;
}
public String getDescription() {
return description;
}
public String getIcon() {
return icon;
}
}
public static class maininfo{
String temp,feels_like,temp_min,temp_max,pressure,humidity;
public String getTemp() {
return temp;
}
public String getFeels_like() {
return feels_like;
}
public String getTemp_min() {
return temp_min;
}
public String getTemp_max() {
return temp_max;
}
public String getPressure() {
return pressure;
}
public String getHumidity() {
return humidity;
}
}
}
此后,在阅读您的回复时,请尝试这种方式。
ArrayList<Weather.weatherinfo> list = response.body().getWeather();
快乐编码
要将响应转换为可用的java对象,您将必须使用Gson或使用Retrofit自动进行。由于您是从调用中获取通用Response
的,所以这意味着您必须自己进行操作。因此,首先将json模式转换为POJO,然后代替
List<Weather> list = new ArrayList<>(((Weather)response.body()));
使用
ResponsePojo responsePojo = gson.fromJson(response.body().toString(), ResponsePojo.class);
但是,应正确设置Retrofit,以便它为您完成转换,而不是手动进行。然后,您将直接从改造调用中找回对象-
Response<ResponsePojo> response = getWeather(locationCode, apiKey).execute();
ResponsePojo responsePojo = response.body()