4

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?

kishidp
  • 1,918
  • 6
  • 23
  • 29

2 Answers2

2

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 }
Tom
  • 6,946
  • 2
  • 47
  • 63
1

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}, 
...]
MaxF
  • 2,123
  • 1
  • 14
  • 17