版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hj7jay/article/details/85089515
一、@JsonView注解的简介
@JsonView是jackson json中的一个注解,Spring webmvc也支持这个注解,它的作用就是控制输入输出后的json视图,控制输出的字段但又不影响类的其他属性。
二、@JsonView注解的使用步骤
1.使用接口来声明多个视图
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
private String username;
private String password;
public String getUsername (){
return username;
}
public void setUsername (String username){
this.username = username;
}
public String getPassword (){
return password;
}
public void setPassword (String password){
this.password = password;
}
@Override
public String toString (){
return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
2.在值对象的get方法上指定视图
import com.fasterxml.jackson.annotation.JsonView;
public class User {
public interface UserSimpleView {};
public interface UserDetailView extends UserSimpleView {};
private String username;
private String password;
@JsonView(UserSimpleView.class)
public String getUsername (){
return username;
}
public void setUsername (String username){
this.username = username;
}
@JsonView(UserDetailView.class)
public String getPassword (){
return password;
}
public void setPassword (String password){
this.password = password;
}
@Override
public String toString (){
return "User{" + "username='" + username + '\'' + ", password='" + password + '\'' + '}';
}
}
3.在controller方法上指定视图
import com.fasterxml.jackson.annotation.JsonView;
import com.knyel.dto.User;
import com.knyel.dto.UserQueryCondition;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.data.domain.Pageable;
import java.util.ArrayList;
import java.util.List;
@RestController
public class UserController {
@RequestMapping(value = "/user",method = RequestMethod.GET)
@JsonView(User.UserSimpleView.class)
public List<User> query(UserQueryCondition userQueryCondition, @PageableDefault(page=1,size=10,sort="username,asc") Pageable pageable){
System.out.println(pageable.getPageNumber());
System.out.println(pageable.getSort());
System.out.println(pageable.getPageSize());
System.out.println(userQueryCondition.toString());
List<User> users=new ArrayList<>();
users.add(new User());
users.add(new User());
users.add(new User());
return users;
}
@RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)
@JsonView(User.UserDetailView.class)
public User getInfo(@PathVariable String id){
User user=new User();
user.setUsername("knyel");
System.out.println(user);
return user;
}
}
4.结果
query查询
[{"username":null},{"username":null},{"username":null}]
getInfo查询
{"username":"knyel","password":null}