Created
February 17, 2015 20:30
-
-
Save NikolaDespotoski/c2c147e80ec950392e36 to your computer and use it in GitHub Desktop.
LoganSquareConverter for Retrofit
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
import com.bluelinelabs.logansquare.LoganSquare; | |
import java.io.IOException; | |
import java.io.OutputStream; | |
import java.lang.reflect.Type; | |
import java.nio.charset.Charset; | |
import retrofit.converter.ConversionException; | |
import retrofit.converter.Converter; | |
import retrofit.mime.TypedInput; | |
import retrofit.mime.TypedOutput; | |
/** | |
* Created by Nikola on 2/17/2015. | |
*/ | |
public class LoganSquareConverter implements Converter { | |
private Charset mCharSet = Charset.forName("UTF-8"); | |
public LoganSquareConverter(Charset charSet) { | |
mCharSet = charSet; | |
} | |
public LoganSquareConverter() { | |
} | |
@Override | |
public Object fromBody(TypedInput body, Type type) throws ConversionException { | |
try { | |
return LoganSquare.parse(body.in(), type.getClass()); | |
} catch (IOException e) { | |
return null; | |
} | |
} | |
@Override | |
public TypedOutput toBody(Object object) { | |
String serialized = LoganSquare.serialize(object); | |
return new LoganSquareTypedOutput(serialized.getBytes(mCharSet)); | |
} | |
private class LoganSquareTypedOutput implements TypedOutput { | |
private byte[] mBytes; | |
LoganSquareTypedOutput(byte[] data){ | |
mBytes = data; | |
} | |
@Override | |
public String fileName() { | |
return null; | |
} | |
@Override | |
public String mimeType() { | |
return "application/json"; | |
} | |
@Override | |
public long length() { | |
return mBytes.length; | |
} | |
@Override | |
public void writeTo(OutputStream out) throws IOException { | |
out.write(mBytes); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment