Skip to content

Instantly share code, notes, and snippets.

@ararog
Created October 23, 2014 14:55
Show Gist options
  • Save ararog/fd1405124d2d64bc9a38 to your computer and use it in GitHub Desktop.
Save ararog/fd1405124d2d64bc9a38 to your computer and use it in GitHub Desktop.
MessagePack converter for retrofit
package br.eti.faces.retrofit.converter;
import org.msgpack.MessagePack;
import org.msgpack.packer.Packer;
import org.msgpack.unpacker.Unpacker;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.reflect.Type;
import retrofit.converter.ConversionException;
import retrofit.converter.Converter;
import retrofit.mime.TypedByteArray;
import retrofit.mime.TypedInput;
import retrofit.mime.TypedOutput;
/**
* Created by ararog on 23/10/14.
*/
public class MsgPackConverter implements Converter {
private static final String MIME_TYPE = "application/x-msgpack";
private MessagePack msgpack;
public MsgPackConverter() {
msgpack = new MessagePack();
}
@Override
public Object fromBody(TypedInput body, Type type) throws ConversionException {
try {
Unpacker unpacker = msgpack.createUnpacker(body.in());
return unpacker.read(type.getClass());
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
public TypedOutput toBody(Object object) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Packer packer = msgpack.createPacker(out);
TypedByteArray byteArray = null;
try {
packer.write(object);
byte[] bytes = out.toByteArray();
byteArray = new TypedByteArray(
MIME_TYPE, bytes);
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment