Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrofit parse JSON dynamic keys

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"
}
like image 766
user3075588 Avatar asked Nov 30 '16 19:11

user3075588


2 Answers

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();
}
like image 78
nbokmans Avatar answered Nov 10 '22 22:11

nbokmans


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

like image 29
John O'Reilly Avatar answered Nov 10 '22 22:11

John O'Reilly