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

如何在ObjectMapper中忽略@JsonIgnoreProperties注解?

问题解决:忽略@JsonIgnoreProperties但保留其他Jackson注解的序列化方案

问题背景

现有如下Java类:

@JsonIgnoreProperties(value = {"myProperty"}, allowSetters = true)
public class Test {

    private String myProperty;

    // getter and setter 已实现
}

使用ObjectMapper序列化时,myProperty未被输出。需要在忽略类上的@JsonIgnoreProperties注解生效逻辑的同时,保留其他Jackson注解的功能。

之前尝试的两个自定义JacksonAnnotationIntrospector均未解决问题:

  • 第一个重写findNameForSerialization,判断逻辑错误,无法识别类上的@JsonIgnoreProperties
  • 第二个重写isAnnotationBundle和hasIgnoreMarker,未覆盖类级别@JsonIgnoreProperties的属性忽略逻辑

正确解决方案

重写JacksonAnnotationIntrospector的_findIgnoredPropertyNames方法,该方法负责解析类级别的@JsonIgnoreProperties中指定的忽略属性列表,直接返回空数组即可跳过属性忽略逻辑,同时保留其他注解的处理:

自定义Introspector实现

public class IgnoreJsonIgnorePropertiesIntrospector extends JacksonAnnotationIntrospector {
    @Override
    protected String[] _findIgnoredPropertyNames(AnnotatedClass ac) {
        // 跳过@JsonIgnoreProperties指定的忽略属性,返回空数组
        return new String[0];
    }
}

测试代码

public class TestMain {
    public static void main(String[] args) {
        Test obj = new Test();
        obj.setMyProperty("this is for test");
        try {
            String json = new ObjectMapper()
                    .setAnnotationIntrospector(new IgnoreJsonIgnorePropertiesIntrospector())
                    .writerWithDefaultPrettyPrinter()
                    .writeValueAsString(obj);
            System.out.println(json);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

运行结果

执行后将输出期望的JSON:

{
  "myProperty" : "this is for test"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 09:43:10