I need to exclude some fields by names before rendering. The list of fields is dynamic, so I can't use annotations.
I've tried to create custom serializer but I can't get field name there.
In GSON I've used ExclusionStrategy
, but Jackson has no such functionality. Is there an equivalent?
The Jackson @JsonIgnore annotation can be used to ignore a certain property or field of a Java object. The property can be ignored both when reading JSON into Java objects and when writing Java objects into JSON.
Ignore All Fields by Type Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly: @JsonIgnoreType public class SomeType { ... } More often than not, however, we don't have control of the class itself.
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
You can ignore the unrecognized fields by configuring the ObjectMapper class: mapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false);
The below example of excluding fields by name is from my blog post, Gson v Jackson - Part 4. (Search for the PropertyFilterMixIn
.) This example demonstrates using a FilterProvider
with a SimpleBeanPropertyFilter
to serializeAllExcept
a user-specified list of field names.
@JsonFilter("filter properties by name") class PropertyFilterMixIn {} class Bar { public String id = "42"; public String name = "Fred"; public String color = "blue"; public Foo foo = new Foo(); } class Foo { public String id = "99"; public String size = "big"; public String height = "tall"; } public class JacksonFoo { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper(); mapper.getSerializationConfig().addMixInAnnotations( Object.class, PropertyFilterMixIn.class); String[] ignorableFieldNames = { "id", "color" }; FilterProvider filters = new SimpleFilterProvider() .addFilter("filter properties by name", SimpleBeanPropertyFilter.serializeAllExcept( ignorableFieldNames)); ObjectWriter writer = mapper.writer(filters); System.out.println(writer.writeValueAsString(new Bar())); // output: // {"name":"James","foo":{"size":"big","height":"tall"}} } }
(Note: The relevant API may have changed slightly with a recent Jackson release.)
While the example does use a seemingly unnecessary annotation, the annotation is not applied to the fields to be excluded. (To help get the API changed to simplify the necessary configuration a bit, please don't hesitate to vote for implementation of issue JACKSON-274.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With