Skip to content

Instantly share code, notes, and snippets.

@aakashns
Created November 7, 2016 06:38
Show Gist options
  • Select an option

  • Save aakashns/70fe33b34a81530dea5944e8c8e89edc to your computer and use it in GitHub Desktop.

Select an option

Save aakashns/70fe33b34a81530dea5944e8c8e89edc to your computer and use it in GitHub Desktop.
Custom Converter Factory for Retrofit 2 ( https://square.github.io/retrofit/ ) to convert the ResponseBody to a JSONObject.
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;
public class JsonConverterFactory extends Converter.Factory {
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return JsonConverter.INSTANCE;
}
final static class JsonConverter implements Converter<ResponseBody, JSONObject> {
static final JsonConverter INSTANCE = new JsonConverter();
@Override
public JSONObject convert(ResponseBody responseBody) throws IOException {
try {
return new JSONObject(responseBody.string());
} catch (JSONException e) {
throw new IOException("Failed to parse JSON", e);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment