簡體   English   中英

Jackson ObjectMapper:如何從序列化中省略(忽略)某些類型的字段?

[英]Jackson ObjectMapper: How to omit (ignore) fields of certain type from serialization?

我如何告訴 Jackson ObjectMapper 忽略某些類型(類)的字段,在我的Object.class的情況下,從序列化?

約束:

  • 無法控制源 class - 它是第三方 class
  • 被序列化的 Class 類型預先未知 - 我猜它不符合 MixIn(s)
  • 此類字段名稱預先未知

為了提供幫助,下面是一個單元測試,期望從序列化中忽略字段objectsListobjectField ,但它的方法不正確,它是按名稱而不是按類型過濾它們。

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\"}}");

}

一種方法是使用自定義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());

如果您使用的是 mixins,您應該能夠使用 @JsonIgnoreType 進行注釋以使其忽略 class。 docs供參考全局忽略 Jackson 中的 class

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM