翻新解析JSON动态密钥

问题描述:

我是Retrofit的新手.如何使用改型解析下面的Json?

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"
}

您可以使模型POJO包含一个Map<String, Champion>进行反序列化以处理动态键.

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

示例:

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

除此之外,我对Retrofit并不熟悉,但是正如评论中的某人所说,反序列化由Gson完成:

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

因此,要基于其他人发布的答案,则可以假定已添加GsonConverterFactory,然后执行以下操作:

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