【问题标题】:Retrofit 2 Serializing JSON Result with dynamic keysRetrofit 2 使用动态键序列化 JSON 结果
【发布时间】:2016-09-02 08:41:08
【问题描述】:

我有一个返回数据的 api,其结构类似于:

{
   "1": {
        "url":"http://www.test.com",
        "count":2
   },
   "3": {
        "url":"http://www.test.com",
        "count":12
   },
   "16": {
        "url":"http://www.test.com",
        "count":42
   }
}

名字就是id。它时常变化,所以我不知道钥匙。

那我该如何序列化呢?

【问题讨论】:

    标签: android json retrofit2


    【解决方案1】:

    Retrofit 可以将这种结构序列化为地图。

    public final Map<String, MyDataStructure> items;
    

    在您的情况下,这将生成一个大小为 3 的地图,其中包含以下内容

    "1" -> { "url":"http://www.test.com", "count":2 }
    "3" -> { "url":"http://www.test.com", "count":12 }
    "16" -> { "url":"http://www.test.com", "count":42 }
    

    【讨论】:

      【解决方案2】:

      我认为您必须使用转换器(GSON 转换器或 Jackson 转换器)并使用 TypeAdapter 解析其中的 JSON 答案。

      private static final Gson GSON = new GsonBuilder()
                  .registerTypeAdapter(ApiEntity.class, new ApiEntityAdapter())
                  .create();
      
      private static final Retrofit RETROFIT = new Retrofit.Builder()
                  ...
                  .addConverterFactory(GsonConverterFactory.create(GSON))
                  .build();
      

      关于TypeAdapter你可以阅读here

      但是如果你能改变api的答案,你最好建一个这样的结构

      [ {"id":1, "url":"http://www.test.com", "count":2},
        {"id":3, "url":"http://www.test.com", "count":12}, 
      ...]
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-11
        • 2016-02-14
        • 2019-05-16
        • 2023-03-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多