Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson filter properties without annotations

public Class User {
    private String name;
    private Integer age;
    ...
}

ObjectMapper om = new ObjectMapper();
om.writeValueAsString(user);

How can I filter properties without using any annotations like @JsonIgnore?

like image 786
Smile Avatar asked Jun 09 '26 06:06

Smile


2 Answers

You have two possible ways using Jackson

Mixin Annotations :- http://www.cowtowncoder.com/blog/archives/2009/08/entry_305.html

JSON Filter :- http://wiki.fasterxml.com/JacksonFeatureJsonFilter

like image 166
dilipl Avatar answered Jun 11 '26 22:06

dilipl


The example of excluding properties by name:

public Class User {
    private String name = "abc";
    private Integer age = 1;
    //getters
}

@JsonFilter("dynamicFilter")
public class DynamicMixIn {
}

User user = new User();
String[] propertiesToExclude = {"age"};
ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Object.class, DynamicMixIn.class);
FilterProvider filterProvider = new SimpleFilterProvider()
                .addFilter("dynamicFilter", SimpleBeanPropertyFilter.serializeAllExcept(propertiesToExclude));
        mapper.setFilterProvider(filterProvider);

mapper.writeValueAsString(user); // {"name":"abc"}

You can instead of DynamicMixIn create MixInByPropName

@JsonIgnoreProperties(value = {"age"})
public class MixInByPropName {
}

ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Object.class, MixInByPropName.class);

mapper.writeValueAsString(user); // {"name":"abc"}

Note: If you want exclude property only for User you can change parameter Object.class of method addMixIn to User.class

Excluding properties by type you can create MixInByType

@JsonIgnoreType
public class MixInByType {
}

ObjectMapper mapper = new ObjectMapper()
      .addMixIn(Integer.class, MixInByType.class);

mapper.writeValueAsString(user); // {"name":"abc"}
like image 24
Beno Arakelyan Avatar answered Jun 11 '26 20:06

Beno Arakelyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!