在不使用GSON或JSONObject的情况下,可以通过重写Converter.Factory来序列化null。以下是实现此方法的步骤:
1.创建NullOnEmptyConverterFactory.java类,并实现Converter.Factory接口。
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
public class NullOnEmptyConverterFactory extends Converter.Factory {
@Override
public Converter responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
final Converter delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
return new Converter() {
@Override
public Object convert(ResponseBody body) throws IOException {
if (body.contentLength() == 0) return null;
return delegate.convert(body);
}
};
}
@Override
public Converter, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
final Converter, RequestBody> delegate = retrofit.nextRequestBodyConverter(this, type, parameterAnnotations, methodAnnotations);
return new Converter
2.在Retrofit实例中添加NullOnEmptyConverterFactory工厂。
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(new NullOnEmptyConverterFactory())
.build();
现在您可以在API响应中正常使用null。