Created
July 9, 2013 19:32
-
-
Save johnfrey99/5960499 to your computer and use it in GitHub Desktop.
Retrofit converter based on Jackson instead of Gson.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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