Skip to content

redission_codec_cn

Shaojin Wen edited this page Apr 14, 2024 · 3 revisions

fastjson 2.0.49版本开始提供Redission的Codec支持。

    1. Maven依赖配置 Codec放在fastjson2-extension中,需要如下的Maven配置,具体使用时请查看最新版本。
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2-extension</artifactId>
    <version>2.0.49</version>
</dependency>

2. JSON Codec

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);

3. JSONB Codec

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);

4. 相关链接

autoTypeFilter介绍 https://github.com/alibaba/fastjson2/wiki/fastjson2_autotype_cn