@JsonView is an annotation in the Jackson JSON, and spring WEBMVC also supports this annotation.
The function of this annotation is to control the JSON after input and output.
Suppose we have a user class that contains a user name and password, and normally if we need to serialize the user class, the password is also serialized, and in general we certainly don't want to see such a situation. But there are some situations where we need to serialize the password, how to solve the two different situations?
It can be solved with @jsonview.
Take a look at the following simple example:
Public classUser { Public InterfaceWithoutpasswordview {}; Public InterfaceWithpasswordviewextendsWithoutpasswordview {}; PrivateString username; PrivateString password; PublicUser () {} PublicUser (string Username, string password) { This. Username =username; This. Password =password; } @JsonView (Withoutpasswordview.class) PublicString GetUserName () {return This. Username; } @JsonView (Withpasswordview.class) PublicString GetPassword () {return This. Password; } }
There is a simple user object that contains two simple properties.
Two interfaces are defined in this object, where Withoutpasswordview refers to a view without a password, withpasswordview refers to a view with a password, and inherits the view of Withoutpasswordview.
This view in the @JsonView can be used not only as an interface, but also as a generic class, or as a view if you have a class attribute.
Inheritance between classes or interfaces is also an inheritance between views, and the inherited view contains the methods of the ancestor view annotations.
@JsonView can be written on a method or a field.
The following code tests the user object above:
Public Static voidMain (string[] args)throwsIOException {objectmapper objectmapper=NewObjectmapper (); //Creating ObjectsUser User =NewUser ("isea533", "123456"); //Serialization ofBytearrayoutputstream BOS =NewBytearrayoutputstream (); Objectmapper.writerwithview (User.withoutpasswordview.class). WriteValue (Bos, user); System.out.println (Bos.tostring ()); Bos.reset (); Objectmapper.writerwithview (User.withpasswordview.class). WriteValue (Bos, user); System.out.println (Bos.tostring ()); }
Create a objectmapper first, and then create a objectwritter of the specified view through the Writerwithview factory method, and then output the results by WriteValue.
Output Result:
{"username": "isea533"} {"username": "isea533", "Password": "123456"}
@JsonView used to be so simple, not too complicated.
@JsonView attributes can be written on the annotations, this is not known whether it is similar to the custom annotations in spring, if anyone who knows can leave a message, thank you.
Also note when using @jsonview in Spring-webmvc, although the annotation allows you to specify multiple views, SPRING-WEBMVC only supports one parameter (view).
Spring Boot @jsonview Brief introduction