Using @jsonview annotations to implement custom return fields

Source: Internet
Author: User

Business Scenario: For example a user object, there are two fields, a username, a password, and an interface to get the user information to return this list of users, but do not want the password field of the user list.

There is also an interface to get this user list, to all fields.

Solution Scenario: We can have a number of methods, such as to get the list after the user list password is all empty, and then use the other annotations to set the field to empty is not displayed

You can also not check the password field in SQL.

But we're going to introduce this annotation to implement this feature. @jsonView

It takes three steps:

    • First: Use interfaces to declare multiple views
    • Second: Specify the view on the Get method of the value object
    • Third: Specify the view on the Controller method

Don't say a lot of words ~ ~ See code------

User.java

 PackageCom.imooc;ImportCom.fasterxml.jackson.annotation.JsonView;ImportLombok. Allargsconstructor;ImportLombok. Setter;/*** Created by knocking the code out of the Kaka * on 2018/4/14 22:58.*/@Setter @allargsconstructor Public classUser { Public Interfaceuserinfo{};  Public InterfaceUserdetailextendsuserinfo{}; PrivateString name; PrivateString password; @JsonView (UserInfo.class)     PublicString GetName () {returnname; } @JsonView (Userdetail.class)     PublicString GetPassword () {returnpassword; }}
View Code

Declare two interfaces (views) in the user object, one to inherit another, you know!!! Then declare the view on the Get method of the field

Controller.java

@GetMapping ("/hello")    @JsonView (user.userinfo. class   public HashMap Hello () {        new  HashMap ();              New User ("Liu", "123");         New User ("Zhang", "456");        Hashmap.put ("U1", user1);        Hashmap.put ("U2", User2);         return hashMap;    }
View Code

Declare the view yourself in the controller and look at the results.

Using @jsonview annotations to implement custom return fields

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.