jackson objectmapper:如何从序列化中省略(忽略)特定类型的字段?

velaa5lx  于 2021-06-27  发布在  Java
关注(0)|答案(2)|浏览(461)

在我的示例中,如何告诉jackson objectmapper忽略某些类型(类)的字段 Object.class ,从序列化?
约束条件:
没有对源类的控制-它是第三方类
被序列化的类类型是未知的-我猜它取消了mixin的资格
此类字段名称预先未知
为了提供帮助,下面是一个单元测试字段 objectsList 以及 objectField 要从序列化中忽略它们,但其方法不正确,它是按名称而不是按类型过滤它们。

public static class FavoriteShows {
    public Simpsons favorite = new Simpsons();
    public BigBangTheory preferred = new BigBangTheory();
}

public static class Simpsons {
    public String title = "The Simpsons";

    public List<Object> objectsList = List.of("homer", "simpson");
    public Object objectField = new HashMap() {{
        put("mr", "burns");
        put("ned", "flanders");
    }};
}

public static class BigBangTheory {
    public String title = "The Big Bang Theory";

    public List<Object> objectsList = List.of("sheldon", "cooper");
    public Object objectField = new HashMap() {{
        put("leonard", "hofstadter");
        put("Raj", "koothrappali");
    }};
}

public abstract static class MyMixIn {
    @JsonIgnore
    private Object objectField;
    @JsonIgnore
    private Object objectsList;
}

@Test
public void test() throws JsonProcessingException {
    // GIVEN
    // Right solution must work for any (MixIn(s) is out of questions) Jackson annotated class
    // without its modification.
    final ObjectMapper mapper = new ObjectMapper()
            .addMixIn(Simpsons.class, MyMixIn.class)
            .addMixIn(BigBangTheory.class, MyMixIn.class);

    // WHEN
    String actual = mapper.writeValueAsString(new FavoriteShows());
    System.out.println(actual);

    // THEN
    // Expected: {"favorite":{"title":"The Simpsons"},"preferred":{"title":"The Big Bang Theory"}}
    assertThat(actual).isEqualTo("{\"favorite\":{\"title\":\"The Simpsons\"},\"preferred\":{\"title\":\"The Big Bang Theory\"}}");

}
5hcedyr0

5hcedyr01#

其中一种方法是使用自定义 AnnotationIntrospector .

class A {

    int three = 3;
    int four = 4;
    B b = new B();

    // setters + getters
}

class B {

    int one = 1;
    int two = 2;

    // setters + getters
}

忽略类型为的所有字段 B :

ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector() {
    @Override
    protected boolean _isIgnorable(Annotated a) {
        return super._isIgnorable(a)
                 // Ignore B.class
                 || a.getRawType() == B.class
                 // Ignore List<B>
                 || a.getType() == TypeFactory.defaultInstance()
                       .constructCollectionLikeType(List.class, B.class);
    }
});

String json = mapper.writeValueAsString(new A());
c3frrgcw

c3frrgcw2#

如果您使用的是mixin,那么应该能够使用@jsonignoretype进行注解,使其忽略类。jackson中全局忽略类的引用文档

相关问题