Skip to content

Instantly share code, notes, and snippets.

@TarekkMA
Last active August 2, 2016 18:35
Show Gist options
  • Save TarekkMA/9aee529c2f974173b183553669981974 to your computer and use it in GitHub Desktop.
Save TarekkMA/9aee529c2f974173b183553669981974 to your computer and use it in GitHub Desktop.
Retrofit 2 Custom/Modified Converter for editing the response before converting

This Code is Modifed from the retrofit2:converter-gson:2.1.0 ###How to use this class ?

  • Go to public T convert(ResponseBody value) method and clean your response as you wish
/**
* Modified by TarekkMA on 8/2/2016.
*/
public class MyJsonConverter extends Converter.Factory {
public static MyJsonConverter create() {
return create(new Gson());
}
public static JsonHandler create(Gson gson) {
return new JsonHandler(gson);
}
private final Gson gson;
private JsonHandler(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonResponseBodyConverter<>(gson, adapter);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new GsonRequestBodyConverter<>(gson, adapter);
}
final class GsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonRequestBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer();
Writer writer = new OutputStreamWriter(buffer.outputStream(), UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter, value);
jsonWriter.close();
return RequestBody.create(MEDIA_TYPE, buffer.readByteString());
}
}
final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Gson gson;
private final TypeAdapter<T> adapter;
GsonResponseBodyConverter(Gson gson, TypeAdapter<T> adapter) {
this.gson = gson;
this.adapter = adapter;
}
@Override
public T convert(ResponseBody value) throws IOException {
String dirty = value.string();
String clean = dirty.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n" +
"<string xmlns=\"http://tempuri.org/\">","").replace("</string>","");
try {
return adapter.fromJson(clean);
} finally {
value.close();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment