Retrofit parse JSON dynamic keys

大憨熊 提交于 2019-12-03 16:07:13

You could make your model POJO contain a Map<String, Champion> to deserialize into, to deal with the dynamic keys.

Example:

public class ChampionData {
    public Map<String, Champion> data;
    public String type;
    public String version;
}

public class Champion {
    public int id;
    public String title;
    public String name;
    public String key;
}

I'm not familiar with Retrofit besides that, but as someone in the comments said, the deserializing is done by Gson:

public ChampionData champions = new Gson().fromJson(json, ChampionData.class);

So to build on to the answer someone else posted, you can then do the following, assuming you've added the GsonConverterFactory:

public interface API {
    @GET("path/to/endpoint")
    Call<ChampionData> getChampionData();
}

Assuming Retrofit2, the first thing you need to do is call following when building your Retrofit instance.

addConverterFactory(GsonConverterFactory.create())

Then it's just a matter of writing a POJO (e.g. MyPojoClass) that maps to the json and then adding something like following to your Retrofit interface.

Call<MyPojoClass> makeRequest(<some params>);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!