如何忽略杰克逊注释?

时间:2014-04-03 07:02:34

标签: 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;
    }

    // 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 进行序列化时

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"}}}

是否可以在不编写自定义序列化程序的情况下实现此目的? 我知道我可以使用混合机制添加注释,但基本上我需要在某些情况下忽略现有注释。

1 个答案:

答案 0 :(得分:2)

我已经使用混合机制解决了我的问题。

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);
相关问题