Retrofit: Custom ConverterFactory answer only
I have a general response from the server:
{
"Error": null,
"Data": {}
}
}
So, I created my own factory converter to get the object inside Data
.
The main idea is to change:
- this
Call<ResponseBase<List<Item>>> getItems();
- to
Call<List<Item>> getItems();
It works fine with responses, but when I try to send and the object in the request with @Body
, the converter fails ...
java.lang.IllegalArgumentException: Unable to create @Body converter for class <package>.data.entities.request.RequestLogin (parameter #1)
...
Caused by: java.lang.IllegalArgumentException: Could not locate RequestBody converter for class <package>.data.entities.request.RequestLogin.
Tried:
* retrofit2.BuiltInConverters
* <package>.data.api.ResponseConverterFactory
This is my custom one Converter.Factory
:
class ResponseConverterFactory extends Converter.Factory {
// constructor
@Override
public Converter<ResponseBody, ?> responseBodyConverter(final Type type, Annotation[] annotations, Retrofit retrofit) {
Type wrappedType = new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[] {type};
}
@Override
public Type getOwnerType() {
return null;
}
@Override
public Type getRawType() {
return ResponseBase.class; // GENERIC CLASS
}
};
Converter<ResponseBody, ?> converter = factory.responseBodyConverter(wrappedType, annotations, retrofit);
return new ResponseConverter(converter);
}
}
How can I use the default converter to serialize the request?
+3
source to share
1 answer
OK ... the simple solution was to override requestBodyConverter
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
factory
- a global variable (GsonConverterFactory), which is set on the constructor
+1
source to share