Java 如何忽略Jackson注释?

Java 如何忽略Jackson注释?,java,json,jackson,Java,Json,Jackson,我有两门课: public class Bar { private String identifier; private String otherStuff; public Bar(){} public Bar(String identifier, String otherStuff) { this.identifier = identifier; this.otherStuff = otherStuff; }

我有两门课:

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
}

大多数情况下都可以,但在某些情况下,我希望在json中有完整的对象,如下面所示:

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

您可以使用MixIn机制并使用两种不同的
ObjectMapper
s。一个
ObjectMapper
可以在需要此自定义序列化程序时使用,另一个
ObjectMapper
可以在不需要时使用。请检查这个问题:@MichałZiober在大多数情况下我需要自定义序列化程序,这就是为什么注释在我的
Foo
类中。我尝试过Mixin机制,我可以用它添加一些序列化程序,但我需要忽略现有的一个。我理解这个问题。主要是希望使用自定义序列化程序序列化此类,但有时希望使用默认序列化程序序列化此类。如果是,您只有一个解决方案:您必须创建两个
ObjectMapper
s对象,然后在第一个选项中启用自定义序列化程序(使用MixIn功能),在第二个选项中您不应该这样做。您也可以尝试使用
MapperFeature。使用\u注释
功能。在一个
ObjectMapper
中,您可以启用它,并且此对象不应读取注释,因此将不会使用自定义序列化程序。您的问题的状态如何?你解决了吗?@MichałZiober我已经按照你的建议使用混合机制解决了我的问题。但我用了不同的方式。你可以检查我的答案。谢谢你帮助我。
{"foo":"foo","barsMap":{"b1":"bar1","b2":"bar2","b3":"bar3"}}
{"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);
}
mapper = new ObjectMapper();
mapper.addMixInAnnotations(Foo.class, FooMixin.class);
jsonString = mapper.writeValueAsString(foo);
System.out.println(jsonString);