簡體   English   中英

如何忽略傑克遜注釋?

[英]How to ignore Jackson annotations?

我有兩節課:

public class Bar {
    private String identifier;
    private String otherStuff;

    public Bar(){}

    public Bar(String identifier, String otherStuff) {
        this.identifier = identifier;
        this.otherStuff = otherStuff;
    }

    // Getters and Setters
}

public class Foo {
    private String foo;

    @JsonSerialize(using=BarsMapSerializer.class)
    @JsonDeserialize(using=BarsMapDeserializer.class)
    private Map<String, Bar> barsMap;

    public Foo(){}
    public Foo(String foo, Map<String, Bar> barsMap) {
        this.foo = foo;
        this.barsMap = barsMap;
    }

    // Getters and Setters
}

當我用代碼對Foo進行sserialize時:

public static void main(String[] args) throws Exception {
    Map<String, Bar> barsMap = new LinkedHashMap<>();
    barsMap.put("b1", new Bar("bar1", "nevermind1"));
    barsMap.put("b2", new Bar("bar2", "nevermind2"));
    barsMap.put("b3", new Bar("bar3", "nevermind3"));
    Foo foo = new Foo("foo", barsMap);

    ObjectMapper mapper = new ObjectMapper();
    String jsonString = mapper.writeValueAsString(foo);
    System.out.println(jsonString);
}

輸出是:

{"foo":"foo","barsMap":{"b1":"bar1","b2":"bar2","b3":"bar3"}}

對於大多數情況來說沒問題,但在某些情況下我希望在我的json中有完整的Bar對象,如下:

{"foo":"foo","barsMap":{"b1":{"identifier":"bar1", "otherStuff":"nevermind1"},"b2":{"identifier":"bar2", "otherStuff":"nevermind2"},"b3":{"identifier":"bar3", "otherStuff":nevermind3"}}}

是否可以在不編寫自定義序列化器的情況下實現此目的 我知道我可以使用混合機制添加注釋,但基本上我需要在某些情況下忽略現有的注釋。

我已經使用混合機制解決了我的問題。

public interface FooMixin {
    @JsonSerialize
    Map<String, Bar> getBarsMap();
    @JsonDeserialize
    void setBarsMap(Map<String, Bar> barsMap);
}

混合使用此接口后,類Foo被序列化為默認序列化程序。 如您所見,您需要添加JsonSerialize / JsonDeserialize注釋而不指定任何類。

下面的代碼顯示了此接口的用法:

mapper = new ObjectMapper();
mapper.addMixInAnnotations(Foo.class, FooMixin.class);
jsonString = mapper.writeValueAsString(foo);
System.out.println(jsonString);

暫無
暫無

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

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