Jackson Misc JSONFilter of the same class

I am trying to use different JsonFilters to serialize objects of the same class.

Imagine the class foo

public class Foo{
    Bar p1;
    Bar p2;
}

and class Bar

@JsonFilter("myFilter")
public class Bar{
    String prop1;
    String prop2;
    String prop3;
}

Now what I want to achieve is setting up different JsonFilters for the variables p1 and p2 in the Foo class.

For instance. for p1, I want to serialize only prop1, and for p2 I want to serialize prop2 and prop3. To get the next json

{
    "p1": { "prop1":"blabla" }
    "p2": { "prop2":"blabla", "prop3":"blabla" }
}

So, I would use the following filter to get only the “prop1” series:

FilterProvider filter = new SimpleFilterProvider().addFilter("myFilter",
    SimpleBeanPropertyFilter.filterOutAllExcept("prop1"));

String json = new ObjectMapper().filteredWriter(filter).writeValueAsString(foo)

But using this will also only serialize p2 with prop1

I would like to create another filter for p2 as follows:

FilterProvider filter2 = new SimpleFilterProvider().addFilter("myFilter",
    SimpleBeanPropertyFilter.filterOutAllExcept("prop2","prop3"));

But I really can’t find how to implement it so that there are different filters for p1 and p2, seeing that they are of the same Foo class.

Thanks for reading, hope someone can help!

+2
1

Jackson 2.3 @JsonFilter . , . :

public class JacksonFilters {
    static class Bar {
        final public String prop1;
        final public String prop2;
        final public String prop3;

        Bar(final String prop1, final String prop2, final String prop3) {
            this.prop1 = prop1;
            this.prop2 = prop2;
            this.prop3 = prop3;
        }
    }

    static class Foo {
        @JsonFilter("myFilter1")
        final public Bar p1;
        @JsonFilter("myFilter2")
        final public Bar p2;

        Foo(final Bar p1, final Bar p2) {
            this.p1 = p1;
            this.p2 = p2;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        final SimpleFilterProvider filterProvider = new SimpleFilterProvider();
        filterProvider.addFilter("myFilter1",
                SimpleBeanPropertyFilter.filterOutAllExcept("prop1"));
        filterProvider.addFilter("myFilter2",
                SimpleBeanPropertyFilter.serializeAllExcept("prop2"));

        final Foo bar = new Foo(new Bar("a", "b", "c"), new Bar("d", "e", "f"));

        final ObjectMapper mapper = new ObjectMapper();
        mapper.setFilters(filterProvider);
        System.out.println(mapper
                        .writerWithDefaultPrettyPrinter()
                        .writeValueAsString(bar));
    }

}

:

{
  "p1" : {
    "prop1" : "a"
  },
  "p2" : {
    "prop1" : "d",
    "prop3" : "f"
  }
}
+3

Source: https://habr.com/ru/post/1671035/


All Articles