如何在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
相关产品推荐
相关产品推荐

