Skip to content

Instantly share code, notes, and snippets.

@jaredsburrows
Last active August 23, 2018 12:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaredsburrows/26e2c2272f7dbea86a00abe4b26503a4 to your computer and use it in GitHub Desktop.
Save jaredsburrows/26e2c2272f7dbea86a00abe4b26503a4 to your computer and use it in GitHub Desktop.
import android.support.annotation.Nullable;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
/**
* https://github.com/square/retrofit/issues/1554#issuecomment-178633697
* https://github.com/square/retrofit/issues/1554#issuecomment-212941985
*/
public final class NullOnEmptyConverterFactory extends Converter.Factory {
private NullOnEmptyConverterFactory() {
}
public static Converter.Factory create() {
return new NullOnEmptyConverterFactory();
}
@Override
public @Nullable Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
final Converter<ResponseBody, ?> delegate = retrofit.nextResponseBodyConverter(this, type, annotations);
return new Converter<ResponseBody, Object>() {
@Override
public Object convert(ResponseBody body) throws IOException {
if (body.contentLength() == 0) {
return null;
}
return delegate.convert(body);
}
};
}
}
@neteinstein
Copy link

By returning "{}" this will crash due to CastClassException

NullOnEmptyConverterFactory$responseBodyConverter$1 cannot be cast to retrofit2.Converter

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment