jetcache fastjson 泛型复杂对象JSON序列 ,反序列化
·
Jetcache fastjson 泛型复杂对象JSON序列 ,反序列化
默认的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);
}
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)