Reputation: 329
I have a list of objects of a class which I am rendering as json to the browser. Now there are certain attributes in the objects which I want to exclude from the json response if certain condition is not met.
So those attributes will be there for some objects of the list and will be absent for the other objects of that list.
How do I achieve that?
Mine is a spring boot application. Jackson is being used.
I am using Transformer for converting Entity to Bean and then ResponseEntity to convert the bean to json.
Please suggest possible solutions.
Thanks.
Upvotes: 2
Views: 2308
Reputation: 16465
Make those values (which you want to be excluded) as null and then make use of the @JsonInclude
annotation to suppress all null values.
@JsonInclude(Include.NON_NULL) class Foo { String bar; }
you can exclude null
values for specific fields too (As opposed to excluding null values for the entire object)
public class Foo { private String field1; private String field2; @JsonInclude(Include.NON_NULL) private String field3; ... ... }
in version 2.x+ the syntax for this annotation is:
@JsonInclude(JsonSerialize.Inclusion.NON_NULL)
Or you can also set the global option:
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
In a Spring Project, objectMapper
is the singleton instance of class ObjectMapper
which you can either @Autowired
or get from ApplicationContext
Upvotes: 4