kishidp kishidp - 1 year ago 104
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": {
"3": {
"16": {

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 Source

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())

private static final Retrofit RETROFIT = new Retrofit.Builder()

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":"", "count":2},
  {"id":3, "url":"", "count":12},