【问题标题】:How to get hashmap response using Retrofit 2如何使用 Retrofit 2 获得 hashmap 响应
【发布时间】:2018-01-15 02:50:06
【问题描述】:

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

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 中得到响应呢?

【问题讨论】:

  • 你能捕捉到你的调用返回的 json 字符串并发布到这里吗?
  • @Ben p.,我在问题中添加了 json 响应。

标签: android hashmap retrofit2


【解决方案1】:

您的方法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) {

        }
});

【讨论】:

  • "datas" 是一个私有变量。
【解决方案2】:

问题是你使用Call&lt;Countries&gt;,而你应该使用Call&lt;Map&lt;String, Model&gt;&gt;。您的回复没有名为“datas”的字段;这只是StringModel 对象的简单映射。

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

【讨论】:

    猜你喜欢
    • 2019-03-13
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 2021-10-19
    相关资源
    最近更新 更多