-
Notifications
You must be signed in to change notification settings - Fork 495
redission_codec_cn
Shaojin Wen edited this page Apr 14, 2024
·
3 revisions
fastjson 2.0.49版本开始提供Redission的Codec支持。
-
- Maven依赖配置 Codec放在fastjson2-extension中,需要如下的Maven配置,具体使用时请查看最新版本。
<dependency>
<groupId>com.alibaba.fastjson2</groupId>
<artifactId>fastjson2-extension</artifactId>
<version>2.0.49</version>
</dependency>
FASTJSON2支持自动类型,需要手工配置autoTypeFilter,如下:
import com.alibaba.fastjson2.support.redission.JSONCodec;
JSONWriter.Feature[] writerFeatures = {JSONWriter.Feature.WriteClassName};
JSONReader.Feature[] readerFeatures = {};
JSONReader.AutoTypeBeforeHandler autoTypeFilter = JSONReader.autoTypeFilter(Bean.class.getName()); // 配置反序列化支持的类,支持前缀配置
JSONCodec codec = new JSONCodec(
JSONFactory.createWriteContext(writerFeatures),
JSONFactory.createReadContext(autoTypeFilter, readerFeatures)
);
Bean bean = new Bean();
bean.name = "abc";
ByteBuf encoded = codec.getValueEncoder()
.encode(bean);
Bean decoded = (Bean) codec.getValueDecoder()
.decode(encoded, null);
assertEquals(bean.name, decoded.name);
JSONB是二进制协议,常用配置是FieldBased,如下:
import com.alibaba.fastjson2.support.redission.JSONBCodec;
JSONWriter.Feature[] writerFeatures = {JSONWriter.Feature.WriteClassName, JSONWriter.Feature.FieldBased};
JSONReader.Feature[] readerFeatures = {JSONReader.Feature.FieldBased};
JSONReader.AutoTypeBeforeHandler autoTypeFilter = JSONReader.autoTypeFilter(Bean.class.getName()); // 配置反序列化支持的类,支持前缀配置
JSONBCodec codec = new JSONBCodec(
JSONFactory.createWriteContext(writerFeatures),
JSONFactory.createReadContext(autoTypeFilter, readerFeatures)
);
Bean bean = new Bean();
bean.name = "abc";
ByteBuf encoded = codec.getValueEncoder()
.encode(bean);
Bean decoded = (Bean) codec.getValueDecoder()
.decode(encoded, null);
assertEquals(bean.name, decoded.name);
autoTypeFilter介绍 https://github.com/alibaba/fastjson2/wiki/fastjson2_autotype_cn