Jetcache fastjson 泛型复杂对象JSON序列 ,反序列化
- 默认的FastJson2 序列化存在问题
- 增强FastJson 支持
- Encode 编码器
- Decode 解码器
默认的FastJson2 序列化存在问题
默认的序列化不能转换List 中的泛型数据类型, 从缓存拿取的list集合对象数据全部都转换成了JSONObject
增强FastJson 支持
Encode 编码器
增加JSON对象类型存储
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alicp.jetcache.support.Fastjson2ValueEncoder;
/**
* @author wangke
* @version 1.0
* @description:
* @date 2024/4/19 9:43
*/
public class JetCacheFastjson2ValueEncoder extends Fastjson2ValueEncoder {
public JetCacheFastjson2ValueEncoder(boolean useIdentityNumber) {
super(useIdentityNumber);
}
@Override
public byte[] apply(Object value) {
return super.apply(value);
}
@Override
protected byte[] encodeSingleValue(Object value) {
// 保存JSON数据对象类型
return JSON.toJSONString(value, JSONWriter.Feature.WriteClassName).getBytes();
}
}
Decode 解码器
增加JSON对象类型解析
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alicp.jetcache.support.Fastjson2ValueDecoder;
import java.nio.charset.StandardCharsets;
/**
* @author wangke
* @version 1.0
* @description:
* @date 2024/4/19 10:13
*/
public class JetCacheFastjson2ValueDecoder extends Fastjson2ValueDecoder {
public static final JetCacheFastjson2ValueDecoder INSTANCE = new JetCacheFastjson2ValueDecoder(true);
public JetCacheFastjson2ValueDecoder(boolean useIdentityNumber) {
super(useIdentityNumber);
}
@Override
protected Object parseObject(byte[] buffer, int index, int len, Class clazz) {
String s = new String(buffer, index, len, StandardCharsets.UTF_8);
// 解析 JSON数据对象类型
return JSON.parseObject(s, clazz, JSONReader.Feature.SupportAutoType);
}
}