加入依赖:json序列化
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
package com.lms.jdk8.serialize;
import com.google.gson.Gson;
import java.io.*;
import java.nio.charset.StandardCharsets;
/**
* @Author: 李孟帅
* @Date: 2021-12-09 21:14
* @Description:
*/
public enum Serializer {
JDK {
@Override
<T> byte[] serialize(T object) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(object);
return bos.toByteArray();
} catch (IOException e) {
throw new RuntimeException("序列化失败", e);
}
}
@Override
<T> T deserialize(byte[] bytes, Class<T> clazz) {
try {
ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
return (T) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
throw new RuntimeException("反序列化失败", e);
}
}
},
JSON {
@Override
<T> byte[] serialize(T object) {
Gson gson = new Gson();
String json = gson.toJson(object);
return json.getBytes(StandardCharsets.UTF_8);
}
@Override
<T> T deserialize(byte[] bytes, Class<T> clazz) {
Gson gson = new Gson();
return gson.fromJson(new String(bytes, StandardCharsets.UTF_8), clazz);
}
};
// 序列化
abstract <T> byte[] serialize(T object);
// 反序列化
abstract <T> T deserialize(byte[] bytes, Class<T> clazz);
}