I am calling a REST service (not mine) using retrofit which either returns a list of objects (if there are multiple) or a single object (if one). I was able to find a similar issue here however the suggestion is to change the API which i don't have control of. I also read this thread which seems to be a good approach but is there a way to handle this using Retrofit?
相关问题
- Jackson Deserialization not calling deserialize on
- How can I create this custom Bottom Navigation on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Bottom Navigation View gets Shrink Down
While the answer from @pirho seems to be applicable, I found out a different and simple solution which worked for me. Hopefully it may help others as well.
You can get the API response data as
Map<String, JsonElement>
in response and then parse it based on your requirement directly. As you can check here if JsonElement is JsonArrayfor ex:
JsonElement ref
Using Gson to get list of items or single model
As the author of the 2nd post you referred I also refer to the implementation of
PostArrayOrSingleDeserializer
described in that answer of mine.When using Gson with Retrofit (Retrofit's converter-gson) you just need to register the adapter with custom
Gson
instance and build theRetrofit
instance with thatGson
instance, see below example helper class:So the
Object
in theJsonDeserializer
namedObjectArrayOrSingleDeserializer
is the DTO you need to check for single instance or array. ReplaceObject
with corresponding DTO and modify deserializer accordingly.