4

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

Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46
  • possible duplicate of [how to specify jackson to only use fields - preferably globally](http://stackoverflow.com/questions/7105745/how-to-specify-jackson-to-only-use-fields-preferably-globally) – Ransom Briggs Feb 15 '12 at 19:56

1 Answers1

3

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));
Community
  • 1
  • 1
Ransom Briggs
  • 3,025
  • 3
  • 32
  • 46