java - Android Retrofit - 无法将响应添加到 List / recyclerview
问题描述
当我得到我的 response.body() 时,它不允许我将其设置为列表。
样品 GSON:
{
"cod": "200",
"message": 0,
"cnt": 5,
"list": [
{
"dt": 1590861600,
"main": {
"temp": 17.74,
"feels_like": 14.52,
"temp_min": 15.99,
"temp_max": 17.74,
"pressure": 1022,
"sea_level": 1022,
"grnd_level": 1021,
"humidity": 51,
"temp_kf": 1.75
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"clouds": {
"all": 82
},
"wind": {
"speed": 3.75,
"deg": 124
},
"sys": {
"pod": "d"
},
"dt_txt": "2020-05-30 18:00:00"
},
班级
public class WeatherResponse {
@SerializedName("cod")
@Expose
private String cod;
@SerializedName("message")
@Expose
private Long message;
@SerializedName("cnt")
@Expose
private Long cnt;
@SerializedName("list")
@Expose
private List<WeatherList> results;
@SerializedName("city")
@Expose
private City city;
代码
private List<WeatherResponse> mWeatherResponseList;
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
Log.d(TAG, "onResponse: server response " + response.toString());
// response code 200 means a successful request
// if successful store the response body in the log
if (response.code() == 200) {
mWeatherResponseList = response.body(); --Throws an error
错误指出不兼容的类型:必需的 Java.util.list - Found WeatherResponse
我这样做了:
list = new ArrayList(Collections.singleton(((response.body())))); 这似乎奏效了。但现在的问题是响应嵌套了 Json。它的一个对象包含 5 个项目的列表。当我尝试在 recyclerview 中显示 5 个项目时,它只显示一个对象,但不显示我真正想要的 5 个项目的嵌套列表
解决方案
您正在尝试访问整个 JSON 对象,但您只需要 JSON 对象中的结果列表。因此您在调用中获得了单个 JSON 对象响应,因此您可以通过这种方式获得结果列表。
private List<WeatherList> mWeatherResponseList;
public void onResponse(Call<WeatherResponse> call, Response<WeatherResponse> response) {
Log.d(TAG, "onResponse: server response " + response.toString());
if (response.code() == 200) {
mWeatherResponseList = response.body().results;
这样你就得到了列表。
推荐阅读
- jvm - 堆栈上有东西时,VerifyError 清空字节码中的堆栈
- java - 如何在 Firebase 实时数据库中读取嵌套数据(哈希图)
- reactjs - 如何获取位于对象数组下的对象的值?
- deep-learning - 如何在 DeepLearning4J 中添加具有指定值的激活层?
- search - Microsoft Edge Chromium - 用于设置默认搜索引擎但不锁定设置的 GPO
- acumatica - 基于 Acumatica 中的联系人选择的客户查找
- php - 当参数作为整数传递时,Laravel 返回零而不是实际的单元格值
- excel - Excel公式在变量变量中查找特定数字
- node.js - 我在从以下 mongoose 的数据中获取特定时间段时遇到问题
- javascript - 使用 NodeJS 事件来实现和更新 React 全局状态怎么样?好的还是坏的模式?