How To Handle Json Response Of Either A List Of Objects Or A Single Object Using Retrofit?
Solution 1:
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.
ObjectMappermapper=newObjectMapper();
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
Retrofitretrofit=newRetrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(JacksonConverterFactory.create(mapper))
.client(okHttpClient)
.build();
Solution 2:
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 JsonArray
for ex:
publicfunparseData(val jsonElement:JsonElement){
val gson = Gson()
if(jsonElementFromServer.isJsonArray()){
//here you can just parse it into some list of array
}else{
//here you can parse using gson to single item element or model
}
}
Solution 3:
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 the Retrofit
instance with that Gson
instance, see below example helper class:
publicclassMyRetrofit {
publicstatic MyAPI getMyApi() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(Object.class,
new ObjectArrayOrSingleDeserializer())
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://example.org")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(MyAPI.class);
}
}
So the Object
in the JsonDeserializer
named ObjectArrayOrSingleDeserializer
is the DTO you need to check for single instance or array. Replace Object
with corresponding DTO and modify deserializer accordingly.
Post a Comment for "How To Handle Json Response Of Either A List Of Objects Or A Single Object Using Retrofit?"