Retrofit 2 使用动态键序列化 JSON 结果 [英] Retrofit 2 Serializing JSON Result with dynamic keys
本文介绍了Retrofit 2 使用动态键序列化 JSON 结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 api,它返回的数据结构类似于:
I have an api that returns the data with a structure similar to this:
{
"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.不时变化,所以不知道关键.
The names are the id. It changes from time to time, so I don't know the keys.
那我如何序列化它?
推荐答案
我认为您必须使用转换器(GSON 转换器或 Jackson 转换器)并使用 TypeAdapter 解析其中的 JSON 答案.
I think you have to use a converter (GSON converter or Jackson converter) and parse JSON answer in it with TypeAdapter.
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,你可以阅读这里
About TypeAdapter you can read here
但是如果你可以改变api答案,你最好构建一个这样的结构
But if you can change api answer, it will be better for you to build a structure like this
[ {"id":1, "url":"http://www.test.com", "count":2},
{"id":3, "url":"http://www.test.com", "count":12},
...]
这篇关于Retrofit 2 使用动态键序列化 JSON 结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文