Reputation: 1948
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
}
}
The names are the id. It changes from time to time, so I don't know the keys.
How do I serialize it then?
Upvotes: 4
Views: 1108
Reputation: 7804
Retrofit can serialise this sort of structure to a map.
public final Map<String, MyDataStructure> items;
In your case this would produce a map of size 3 containing the following
"1" -> { "url":"http://www.test.com", "count":2 }
"3" -> { "url":"http://www.test.com", "count":12 }
"16" -> { "url":"http://www.test.com", "count":42 }
Upvotes: 2
Reputation: 2123
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();
About TypeAdapter you can read here
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},
...]
Upvotes: 1