Skip to content

Instantly share code, notes, and snippets.

@fathonyfath
Created January 30, 2016 02:09
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fathonyfath/b6aa8f6f9e05d148a216 to your computer and use it in GitHub Desktop.
Save fathonyfath/b6aa8f6f9e05d148a216 to your computer and use it in GitHub Desktop.
Converter factory for Retrofit 2 which is convert response to primitive type class such as Integer, Float, Double, Boolean, etc. For now there are only String, Integer, Double, and Boolean converter. You can expand it by yourself easily.
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
/**
* Created by bradhawk on 1/29/2016.
*/
public class PrimitiveConverterFactory extends Converter.Factory {
public static PrimitiveConverterFactory create() {
return new PrimitiveConverterFactory();
}
private PrimitiveConverterFactory() {
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
if (type == String.class) {
return new Converter<ResponseBody, String>() {
@Override
public String convert(ResponseBody value) throws IOException {
return value.string();
}
};
} else if(type == Integer.class) {
return new Converter<ResponseBody, Integer>() {
@Override
public Integer convert(ResponseBody value) throws IOException {
return Integer.valueOf(value.string());
}
};
} else if(type == Double.class) {
return new Converter<ResponseBody, Double>() {
@Override
public Double convert(ResponseBody value) throws IOException {
return Double.valueOf(value.string());
}
};
} else if(type == Boolean.class) {
return new Converter<ResponseBody, Boolean>() {
@Override
public Boolean convert(ResponseBody value) throws IOException {
return Boolean.valueOf(value.string());
}
};
}
return null;
}
}
@Robbypatel1357
Copy link

Hello how it used
?
plz give one example when i used error accure

@maxpinto
Copy link

Thanks @fathonyfath

@felixeduardo15
Copy link

sample please

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