import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtobufIOUtil;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
public class ProtoBufUtil {
@SuppressWarnings("unchecked")
public static <T> byte[] serializer(T o) {
Class<T> clzz = (Class<T>) o.getClass();
Schema<T> schema = RuntimeSchema.getSchema(clzz);
return ProtobufIOUtil.toByteArray(o, schema, LinkedBuffer.allocate(1024 * 1024));
}
public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
Schema<T> schema = RuntimeSchema.getSchema(clazz);
ProtostuffIOUtil.mergeFrom(bytes, obj, schema);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return obj;
}
@SuppressWarnings("unchecked")
public static <T> String serializerToString(T o) {
Class<T> clzz = (Class<T>) o.getClass();
Schema<T> schema = RuntimeSchema.getSchema(clzz);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
String string = "";
try {
ProtobufIOUtil.writeTo(byteArrayOutputStream, o, schema, LinkedBuffer.allocate(1024 * 1024));
string = byteArrayOutputStream.toString("ISO-8859-1");
} catch (IOException e) {
e.printStackTrace();
}
return string;
}
public static <T> T deserializerFromStr(String str, Class<T> clazz) {
T obj = null;
try {
obj = clazz.newInstance();
Schema<T> schema = RuntimeSchema.getSchema(clazz);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(str.getBytes("ISO-8859-1"));
ProtostuffIOUtil.mergeFrom(byteArrayInputStream, obj, schema);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return obj;
}
}
序列化之protostuff
猜你喜欢
转载自blog.csdn.net/u013560667/article/details/81665730
今日推荐
周排行