简体   繁体   中英

How do I configure a Jackson ObjectMapper to show only whitelist properties?

How do I configure an ObjectMapper to map only properties annotated with JsonProperty? (does not have to be this particular annotation, but this seemed the most sensible)

I am looking for something that works like Gson's @Expose annotation and GsonBuilder().excludeFieldsWithoutExposeAnnotation().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
    }
}

Thanks, Ransom

From duplicate question except I do not want fields to be used either.

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM