Skip to content

Instantly share code, notes, and snippets.

@koleshop
Created December 11, 2015 07:41
Show Gist options
  • Save koleshop/4d87716146d4d4ff66b2 to your computer and use it in GitHub Desktop.
Save koleshop/4d87716146d4d4ff66b2 to your computer and use it in GitHub Desktop.
import com.google.api.client.extensions.android.json.AndroidJsonFactory;
import com.google.api.client.json.GenericJson;
import com.google.api.client.json.JsonFactory;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class SerializationUtil {
private static final JsonFactory JSON_FACTORY = new AndroidJsonFactory();
public static byte[] getSerializableFromGenericJson(Object value) throws Exception {
byte[] outputbytes = null;
if (value instanceof GenericJson) {
outputbytes = JSON_FACTORY.toByteArray(value);
} else {
ByteArrayOutputStream output = new ByteArrayOutputStream();
ObjectOutputStream objectstream = new ObjectOutputStream(output);
objectstream.writeObject(value);
objectstream.close();
outputbytes = output.toByteArray();
}
return outputbytes;
}
public static <T> T getGenericJsonFromSerializable(byte[] serializableObject, Class<T> outclass) throws Exception {
if (serializableObject[0] == '{' && serializableObject[1] == '"' && serializableObject[serializableObject.length-1] == '}') {
// Looks like JSON...
return JSON_FACTORY.fromString(new String(serializableObject, "UTF-8"), outclass);
} else {
ByteArrayInputStream input = new ByteArrayInputStream(serializableObject);
ObjectInputStream objectstream = new ObjectInputStream(input);
Object value = objectstream.readObject();
objectstream.close();
return outclass.cast(value);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment