You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为父类与子类分别使用自定义JSON序列化器?

嘿,我帮你把这段代码整理成规范的Markdown格式,还补充了完整的序列化器实现方案,这样你就能直接用啦~

自定义Jackson序列化器处理父类与子类场景

1. 父类A与子类B的定义

public class A {
    public final String primaryKey;
    A(String primaryKey) {
        this.primaryKey = primaryKey;
    }
}

public class B extends A {
    public final String secondaryKey;
    B(String primaryKey, String secondaryKey) {
        super(primaryKey);
        this.secondaryKey = secondaryKey;
    }
}

2. 完善后的自定义序列化器ASerializer

你之前给出的序列化器代码没写完,这里补充完整实现,让它既能序列化父类A,也能自动识别子类B并序列化其专属字段:

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

import java.io.IOException;

public class ASerializer extends StdSerializer<A> {
    // 无参构造是Jackson实例化序列化器必需的
    public ASerializer() {
        this(null);
    }

    public ASerializer(Class<A> t) {
        super(t);
    }

    @Override
    public void serialize(A value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeStartObject();
        // 先序列化父类的primaryKey字段
        gen.writeStringField("primaryKey", value.primaryKey);
        
        // 判断如果是子类B的实例,额外序列化secondaryKey
        if (value instanceof B) {
            B bInstance = (B) value;
            gen.writeStringField("secondaryKey", bInstance.secondaryKey);
        }
        
        gen.writeEndObject();
    }
}

3. 序列化器的两种使用方式

方式一:直接在实体类上标注注解

在父类A上添加@JsonSerialize注解指定序列化器,这样所有A及其子类的实例都会用这个序列化器:

import com.fasterxml.jackson.databind.annotation.JsonSerialize;

@JsonSerialize(using = ASerializer.class)
public class A {
    // 类内容保持不变
}

方式二:在ObjectMapper中注册序列化器

如果不想修改实体类代码,可以在配置Jackson的ObjectMapper时注册这个序列化器:

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;

public class SerializationTest {
    public static void main(String[] args) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        SimpleModule customModule = new SimpleModule();
        customModule.addSerializer(A.class, new ASerializer());
        mapper.registerModule(customModule);
        
        // 测试序列化子类B的实例
        B testB = new B("main-key-001", "sub-key-001");
        String jsonResult = mapper.writeValueAsString(testB);
        System.out.println(jsonResult);
        // 输出结果:{"primaryKey":"main-key-001","secondaryKey":"sub-key-001"}
    }
}

内容的提问来源于stack exchange,提问作者morbilli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:41:45