Retrofit parse JSON dynamic keys

我的梦境 提交于 2019-12-21 05:02:20

问题


I'm a newbie in Retrofit. How to parse the Json below using retrofit?

{
   "data": {
      "Aatrox": {
         "id": 266,
         "title": "a Espada Darkin",
         "name": "Aatrox",
         "key": "Aatrox"
      },
      "Thresh": {
         "id": 412,
         "title": "o Guardião das Correntes",
         "name": "Thresh",
         "key": "Thresh"
       }
   },
   "type":"champion",
   "version":"6.23.1"
}

回答1:


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();
}



回答2:


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>);



来源:https://stackoverflow.com/questions/40896993/retrofit-parse-json-dynamic-keys

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