如何配置Jackson ObjectMapper以仅显示白名单属性?

时间:2012-02-15 18:21:57

标签: java json jackson

如何配置ObjectMapper以仅映射使用JsonProperty注释的属性? (不一定是这个特别的注释,但这似乎是最明智的)

我正在寻找像Gson的@Expose注释和GsonBuilder()。的东西.exportsFieldsWithoutExposeAnnotation()。create()serializer Example

class Foo {
    public String secret;

    @JsonProperty
    public String biz;
}

class FooTest {
    public static void main(String[] args) {
        ObjectMapper m = new ObjectMapper();
        // configure the mapper

        Foo foo = new Foo();
        foo.secret = "secret";
        foo.biz = "bizzzz";
        System.out.println(m.writeValueAsString(foo));
        // I want {"biz": "bizzzz"}

        m.readValue("{\"secret\": \"hack\", \"biz\": \"settable\"}", Foo.class);
        // I want this to throw an exception like secret does not exist
    }
}

谢谢,赎金

1 个答案:

答案 0 :(得分:2)

来自duplicate question,但我不想使用字段。

ObjectMapper mapper = new ObjectMapper();
mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.NONE)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));