I have an object that I would like to serialize with an attribute in one part of my program, but without in a different part. I also have an ObjectMapper which is extensively customized that I use for both serializations. My first inclination was to use a Mixin to tweak if the attribute is shown, but it seems that you can only put those on the ObjectMapper and not on a reader returned by the ObjectMapper. Basically the code I would like to be able to write would look like the following.
ObjectMapper myMapper = new ObjectMapper(); // in reality there is a lot of customization
Foo foo = myMapper.reader().withMixin(Foo.class, FooMixin.class).readValue(jsonParser, Foo.class);
ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.
Jackson mixins is a mechanism to add Jackson annotations to classes without modifying the actual class. It was created for those cases where we can't modify a class such as when working with third-party classes. We can use any Jackson annotation but we don't add them directly to the class.
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.
Overview So when Jackson is reading from JSON string, it will read the property and put into the target object. But when Jackson attempts to serialize the object, it will ignore the property. For this purpose, we'll use @JsonIgnore and @JsonIgnoreProperties.
Correct. You can not change mix-ins on-the-fly, however: since they are used for introspection of (de)serializers, and results (actual (de)serializers) are cached, they must be added as part of the initial configuration.
This is why neither ObjectReader
nor ObjectWriter
exposes methods to change mix-ins: they only allow changing of things that can be dynamically changed, on per-call basis.
But perhaps mix-ins are not the best way to do this: have you considered using JSON Views instead? Active view in use can be changed separately for each (de)serialization.
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