使用Retrofit 2在根处解析动态json密钥

时间:2016-12-21 14:55:51

标签: android json retrofit2

我在解析一些简单的json时遇到了问题,尽管root键是动态的。我从其他答案中知道我需要使用地图,但它不起作用。如何使用根元素的地图?

JSON始终是一个具有一个数组列表的根密钥:

示例1

{
  "publishers": [
      "America's Best Comics",
      "DC Comics",
      "Devil's Due",
      "IDW Publishing",
      "Image",
      "Kodansha",
      "Oni Press",
      "Valiant",
      "Vertigo"
  ]
}

示例2

{
  "series": [
      "All-Flash Quarterly",
      "Flash Annual",
      "Flash Comics",
      "Green Arrow",
      "Green Lantern",
      "Impulse",
      "The Flash",
      "The Flash Annual",
      "Wonder Woman"
  ]
}

型号:

public class EntityList {
    private Map<String, List<String>> entities;

    public Map<String, List<String>> getEntities() {
        return entities;
    }

    public void setEntities(Map<String, List<String>> entities) {
        this.entities = entities;
    }

}

Retrofit call的相关部分:

call.enqueue(new Callback<EntityList>() {

    @Override
    public void onResponse(Call<EntityList> call, Response<EntityList> response) {
        if(response.isSuccessful()){

            Map<String, List<String>> entityList= response.body().getEntities();

            for (String mapKey :  maps.keySet()) {
                Log.d("Map","mapKey : "+mapKey+" , mapValue : "+maps.get(mapKey));
            }


        } else {
            ...
        }
    }

1 个答案:

答案 0 :(得分:2)

您的顶级是Map,但您正在尝试反序列化并包含地图的对象。摆脱EntityList课程并使用Map<String, List<String>>作为目标。

call.enqueue(new Callback<EntityList>() {

    @Override
    public void onResponse(Call<Map<String, List<String>>> call, Response<Map<String, List<String>>> response) {
        if(response.isSuccessful()){

            Map<String, List<String>> entityList = response.body();

            for (String mapKey :  maps.keySet()) {
                Log.d("Map","mapKey : "+mapKey+" , mapValue : "+maps.get(mapKey));
            }


        } else {
            ...
        }
    }

您还需要更新界面以返回Call<Map<String, List<String>>>