8

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"
}
Community
  • 1
  • 1
user3075588
  • 123
  • 1
  • 7
  • You don't parse with Retrofit - You deserialize / parse with Gson. – OneCricketeer Nov 30 '16 at 20:35
  • 3
    Anyways, `data` should be a list. So, `"data": [{ "name": "Aatrox", ...}, {"name": "Thresh", ...}]`. That will make it more suited for the format expected by a Gson POJO class – OneCricketeer Nov 30 '16 at 20:37

2 Answers2

14

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();
}
nbokmans
  • 5,492
  • 4
  • 35
  • 59
1

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

John O'Reilly
  • 10,000
  • 4
  • 41
  • 63