I have a Spring AOP service which intercepts a lot of different third-party controllers endpoints. My service runs an endpoint, gets the result DTO, serialize DTO to json with ObjectMapper, sends json to Kafka and return the DTO outside. The problem is: the service shouldn’t serialise fields of particular types (e.g MultipartFile). I can’t use @JsonIgnore annotation, because DTO should be returned outside without changes.
Can I make ObjectMapper skip fields of certain types? Or, maybe, copy the DTO and set this fields to null with reflection?
Question posted in Json
Our archive of expertly curated questions and answers provides insights and solutions to common problems related to this popular data interchange format. From parsing and manipulating JSON data to integrating it with various programming languages and web services, our archive has got you covered. Start exploring today and take your JSON skills to the next level
Our archive of expertly curated questions and answers provides insights and solutions to common problems related to this popular data interchange format. From parsing and manipulating JSON data to integrating it with various programming languages and web services, our archive has got you covered. Start exploring today and take your JSON skills to the next level
3
Answers
I have changeable list of prohibited classes in YAML properties file, so I can't use mixins. The task was solved in this way:
Always remember that Jackson is literal magic and is endlessly customizable 🙂
There are many ways to achieve what you want. Mixins are an easy one.
Mix-ins
Let’s suppose you have the following DTO class and want to exclude
File
:You can create a mix-in such as:
And then use it when serializing:
Instead of
@JsonIgnoreType
, you could have also mixed-in@JsonIgnore
to thefile
field inSimpleDTO
or@JsonIgnoreProperties(value = { "file" })
or any other Jackson annotation. Here’s an overview of annotations used to ignore fields.Note: Do not create a new
ObjectMapper
each time. Configure one instance for serialization and share it forever.Programmatic configuration
Mix-ins let you add annotations from the outside, but annotations are still static configuration. If you have to dynamically choose what to ignore, annotations, mixed-in or not, won’t suffice. Jackson, being magic and all, lets you achieve programmatically anything that can be done via annotations:
And then use it when serializing:
By overriding other methods from
NopAnnotationIntrospector
, you can emulate other annotations,@JsonIgnore
and others.Note: Again, create an
ObjectMapper
only once.you can use an object mapper to overcome this or can be used getDeclaredFields method to build a logic to remove unwanted attributes and return