使用Retrofit 2序列化具有动态键的JSON结果

4

我有一个 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。它们会随着时间的推移而更改,因此我不知道它们的键。

那么我该如何对其进行序列化呢?

2个回答

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

1
我认为您需要使用转换器(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,您可以在这里阅读。
但是,如果您可以更改API的答案,最好构建像这样的结构。
[ {"id":1, "url":"http://www.test.com", "count":2},
  {"id":3, "url":"http://www.test.com", "count":12}, 
...]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接