如何使用改造 2 获取哈希图响应



我正在尝试使用改装 2 获取 json 对象响应。我使用哈希图,因为键是动态的。这是我的响应类:

public class Countries {
private Map<String, Model> datas;
public Map<String, Model> getDatas() {
return datas;
}
}

Model类是:

public class Model {
@SerializedName("country_name")
private String country_name;
@SerializedName("continent_name")
private String continent_name;
public String getCountry_name() {
return country_name;
}
public String getContinent_name() {
return continent_name;
}
}

到目前为止,我已经尝试像这样处理响应:

call.enqueue(new Callback<Countries>() {
@Override
public void onResponse(Call<Countries> call, Response<Countries> response) {
Map<String, Model> map = new HashMap<String, Model>();
map = response.body().getDatas();
for (String keys: map.keySet()) {
// myCode;
}
}
@Override
public void onFailure(Call<Countries> call, Throwable t) {
}
});

并且发生此错误:

java.lang.NullPointerException:尝试调用接口方法 'java.util.Set java.util.Map.keySet((' 在空对象引用上

JSON 响应如下所示:

{
"0": {
"country_name": "Argentina",
"continent_name": "South America"
},
"1": {
"country_name": "Germany",
"continent_name": "Europe"
}
}

那么如何在HashMap中获得响应呢?

问题是你在应该使用Call<Map<String, Model>>的时候使用了Call<Countries>。您的响应没有名为"datas"的字段;它只是一张StringModel对象的普通地图。

删除Countries类,并将网络代码中对它的所有引用替换为Map<String, Model>

您的方法getDatas()重新运行null,因为您没有将数据分配给它。

您应该这样做来获取数据:

map = response.body().datas;

而不是:

map = response.body().getDatas();

您还应该替换此

private Map<String, Model> datas;

public Map<String, Model> datas;

您的代码应如下所示。

call.enqueue(new Callback<Countries>() {
@Override
public void onResponse(Call<Countries> call, Response<Countries> response) {
Map<String, Model> map = new HashMap<String, Model>();
map = response.body().datas;
for (String keys: map.keySet()) {
// myCode;
}
}
@Override
public void onFailure(Call<Countries> call, Throwable t) {
}
});