我有来自服务器的通用响应:
{
"Error": null,
"Data": {}
}
}
所以我创建了一个自定义转换器工厂,只获取Data
内的对象。
主要想法是改变:
Call<ResponseBase<List<Item>>> getItems();
Call<List<Item>> getItems();
它可以很好地处理响应,但是当我尝试使用@Body
发送和反对请求时转换器崩溃...
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
这是我的自定义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);
}
}
如何让它使用默认转换器进行请求序列化?
答案 0 :(得分:1)
好的...简单的解决方案是覆盖requestBodyConverter
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return factory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
factory
是一个全局变量(GsonConverterFactory),它在构造函数上设置