翻新解析JSON动态密钥 [英] Retrofit parse JSON dynamic keys

查看:122
本文介绍了翻新解析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();
}

这篇关于翻新解析JSON动态密钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆