kishidp kishidp - 3 months ago 33
JSON Question

Retrofit 2 Serializing JSON Result with dynamic keys

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?

Answer

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}, 
...]