Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add a Jackson mixin to a reader and not to the objectmapper?

Tags:

java

json

jackson

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);
like image 651
Ransom Briggs Avatar asked Aug 06 '12 14:08

Ransom Briggs


People also ask

How do I ignore properties in ObjectMapper?

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.

How does Jackson Mixins work?

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.

How do I ignore properties in Jackson?

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.

How do you tell Jackson to ignore a field during deserialization?

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.


1 Answers

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.

like image 79
StaxMan Avatar answered Nov 08 '22 18:11

StaxMan