I want to receive items using retrofit and parse them into a Java list. However, the server response is not a JSON array but a JSON object containing the items. That is why retrofit cannot just convert the response into a java list.
The response looks something like this:
{
"4": {
"key": "value",
...
},
"5": {
...
},
...
}
Usually, I would try to receive the items like this:
@GET("items")
Call<List<Item>> getItems();
But this obviously does not work and Retrofit responds: Expected BEGIN_ARRAY but was BEGIN_OBJECT
What is my best option to convert this object into a java list using retrofit?
I'd personally do this in 2 steps to avoid having to write a custom adapter for the deserialization.
I'd write the interface like:
@GET("items")
Call<Map<String, Item>> getItems();
And once you'd call the API on the response I'd just call values()
.
Things to take into consideration is that because the API returns a map and not a list, there's no guarantee that the order of any list you'd produce would be consistent. The json standard doesn't define any order for objects unless they're in a json array.