Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson's @JsonView, @JsonFilter and Spring

Can one use the Jackson @JsonView and @JsonFilter annotations to modify the JSON returned by a Spring MVC controller, whilst using MappingJacksonHttpMessageConverterand 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.

like image 908
EngineerBetter_DJ Avatar asked Oct 03 '11 15:10

EngineerBetter_DJ


People also ask

Does spring use Jackson?

Spring supports Jackson @JsonView annotation directly and can be leveraged to customize, control the serialization/deserialization of REST API response and request body data.

What is Jackson in spring boot?

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 .

What is JsonProperty annotation?

@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.

What is JsonView annotation?

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.


1 Answers

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

UPDATE

Follow this link. Explains with an example the @JsonView annotation.

like image 179
Georgios Syngouroglou Avatar answered Sep 22 '22 06:09

Georgios Syngouroglou