Search code examples
javajsonserializationjacksongson

Jackson: Serialize only marked fields


I am trying to do something which was quite easy in gson. Since I switched to Jackson as serializer, I couldn't figure out how to implement this:

I want to serialize only fields that have been marked by an Annotation. GSON code would be:

class Foo {
    @Expose
    public String sometext="Hello World";
    @Expose
    public int somenumber=30;
    public float noop=1.0;
    ...
 }

which should result in (JSON)

 {
    Foo: {
        sometext:'Hello World',
        somenumber: 30
    }
 }

(Syntax errors may be ignored - source is just for demonstration)

So what's the Jackson counterpart for gson's @Expose and new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();?


Solution

  • There seems to be a way to configure ObjectMapper to ignore all non annotated fields.

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

    Source