Java中类对象序列化和反序列化转换大法(精简)
1.pom.xml中添加相关依赖
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-api</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.10</version>
</dependency>
2.添加一个自定义工具类
/**
* protostuff 序列化工具类,基于protobuf封装
*/
public class ProtostuffHelper {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
private static <T> Schema<T> getSchema(Class<T> clazz) {
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
if (schema == null) {
schema = RuntimeSchema.getSchema(clazz);
if (schema != null) {
cachedSchema.put(clazz, schema);
}
}
return schema;
}
/**
* 序列化
*
* @param t
* @return
*/
public static <T> byte[] serializer(T t) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) t.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(clazz);
return ProtostuffIOUtil.toByteArray(t, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 反序列化
*
* @param bytes
* @param clazz
* @return
*/
public static <T> T deserializer(byte[] bytes, Class<T> clazz) {
try {
T t = clazz.newInstance();
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(bytes, t, schema);
return t;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
// 下面举例用法
@Accessors(chain = true)
@Builder(toBuilder = true)
@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@JsonIgnoreProperties(ignoreUnknown = true)
public static class User{
String username;
String password;
}
public static void main(String[] args) {
byte[] bytes = ProtostuffHelper.serializer(User.builder().username("admin").password("admin").build());
User user = ProtostuffHelper.deserializer(bytes, User.class);
System.out.println(user);
}
}
搞定,接下来就可以自由使用啦,其转换效率要高于类对象与JSONString互转~
喜欢秋天温暖的阳光和一杯沁人心脾的下午茶~