Can one use the Jackson @JsonView
and @JsonFilter
annotations to modify the JSON returned by a Spring MVC controller, whilst using MappingJacksonHttpMessageConverter
and Spring's @ResponseBody
and @RequestBody
annotations?
public class Product { private Integer id; private Set<ProductDescription> descriptions; private BigDecimal price; ... } public class ProductDescription { private Integer id; private Language language; private String name; private String summary; private String lifeStory; ... }
When the client requests a collection of Products
, I'd like to return a minimal version of each ProductDescription
, perhaps just its ID. Then in a subsequent call the client can use this ID to ask for a full instance of ProductDescription
with all properties present.
It would be ideal to be able to specify this on the Spring MVC controller methods, as the method invoked defines the context in which client was requesting the data.
Spring supports Jackson @JsonView annotation directly and can be leveraged to customize, control the serialization/deserialization of REST API response and request body data.
Jackson. Jackson is a suite of data-processing tools for Java. It allows to read and write data in JSON, Avro, BSON, CBOR, CSV, Smile, (Java) Properties, Protobuf, XML or YAML format. Jackson is auto-configured. It comes with the spring-boot-starter-json .
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
The JsonView annotation can be used to include/exclude a property during the serialization and deserialization process dynamically. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from Java object using the writerWithView() method.
This issue is solved!
Follow this
Add support for Jackson serialization views
Spring MVC now supports Jackon's serialization views for rendering different subsets of the same POJO from different controller methods (e.g. detailed page vs summary view). Issue: SPR-7156
This is the SPR-7156.
Status: Resolved
Description
Jackson's JSONView annotation allows the developer to control which aspects of a method are serialiazed. With the current implementation, the Jackson view writer must be used but then the content type is not available. It would be better if as part of the RequestBody annotation, a JSONView could be specified.
Available on Spring ver >= 4.1
Follow this link. Explains with an example the @JsonView annotation.
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