Use @jsonView annotation to implement custom return fields

Business scenario: For example, a User object has two fields, a username and a password. There is an interface for obtaining user information that needs to return the User list, but does not want the password field of the User list.

There is also an interface to get the User list and all fields.

 

Solution scenario: We can have a variety of methods, for example, after obtaining the list, set all the passwords of the user list to be empty, and then use other annotations to set the empty fields not to be displayed

You can also not check the password field in sql.

 

But we are going to introduce this annotation to achieve this functionality. @jsonView  

Three steps are required:

  • 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

Not much to say~~~Look at the code------"

User.java

package com.imooc;

import com.fasterxml.jackson.annotation.JsonView;
import lombok.AllArgsConstructor;
import lombok.Setter;

/**
 * Created by Kakarot who wrote the code
 * on 2018/4/14 22:58.
 */
@Setter
@AllArgsConstructor
public class User {
    public interface UserInfo{};
    public interface UserDetail extends UserInfo{};
    private String name;
    private String password;
    @JsonView(UserInfo.class)
    public String getName() {
        return name;
    }
    @JsonView(UserDetail.class)
    public String getPassword() {
        return password;
    }
}
View Code

 

Declare two interfaces (views) in the user object, one inherits the other, you know! ! ! Then declare the view on the field's get method

Controller.java

@GetMapping("/hello")
    @JsonView(User.UserInfo.class)
    public HashMap hello() {
        HashMap hashMap = new HashMap();
        User user1 = new User("liu","123");
        User user2 = new User("zhang","456");
        hashMap.put("u1",user1);
        hashMap.put("u2",user2);
        return hashMap;
    }
View Code

Declare the view in the controller and see the result for yourself.

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324382929&siteId=291194637