Skip to content

Instantly share code, notes, and snippets.

@johnfrey99
Created July 9, 2013 19:32
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 johnfrey99/5960499 to your computer and use it in GitHub Desktop.
Save johnfrey99/5960499 to your computer and use it in GitHub Desktop.
Retrofit converter based on Jackson instead of Gson.
public class JacksonConverter implements Converter
{
private final ObjectMapper mapper;
public JacksonConverter(ObjectMapper mapper)
{
this.mapper = mapper;
}
@Override public Object fromBody(TypedInput body, Type type) throws ConversionException
{
String charset = "UTF-8";
if (body.mimeType() != null)
{
charset = MimeUtil.parseCharset(body.mimeType());
}
InputStreamReader isr = null;
try
{
isr = new InputStreamReader(body.in(), charset);
return mapper.readValue(isr, TypeFactory.rawClass(type));
}
catch (IOException e)
{
throw new ConversionException(e);
}
finally
{
if (isr != null)
{
try
{
isr.close();
}
catch (IOException ignored)
{
}
}
}
}
@Override public TypedOutput toBody(Object object)
{
try
{
return new JsonTypedOutput(mapper.writeValueAsBytes(object));
}
catch (JsonProcessingException e)
{
throw new AssertionError(e);
}
}
private static class JsonTypedOutput implements TypedOutput
{
private final byte[] jsonBytes;
JsonTypedOutput(byte[] jsonBytes)
{
this.jsonBytes = jsonBytes;
}
@Override public String fileName()
{
return null;
}
@Override public String mimeType()
{
return "application/json; charset=UTF-8";
}
@Override public long length()
{
return jsonBytes.length;
}
@Override public void writeTo(OutputStream out) throws IOException
{
out.write(jsonBytes);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment