-
@JsonView
可以过滤pojo的属性,使Controller在返回json时候,pojo某些属性不返回,比如User的密码,一般是不返回的,就可以使用这个注解。
- 代码:
package jackson;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;
/**
* @author micocube
* projectName: utils4j
* packageName: jackson
* email: ldscube@gmail.com
* createTime: 2019-07-05 14:12
* version: 0.1
* description:
*/
public class JsonViewTest {
public interface SimpleView{};
public interface DetailView extends SimpleView{} ;
private static class User{
static ObjectMapper objectMapper = new ObjectMapper();
private String age;
@JsonView(SimpleView.class)
private String userName;
@JsonView(DetailView.class)
private String password;
private String sex;
public static String getSimpleView()throws Exception{
User user = getUser();
return objectMapper.writerWithView(SimpleView.class).writeValueAsString(user);
}
/**
* @return
* @throws Exception
*/
public static String getDetailView()throws Exception{
User user = getUser();
// 使用SpringMVC的话,可以不用这么写,直接配置MappingJackson2HttpMessageConverter转换器就行
// AbstractJackson2HttpMessageConverter/writeInternal:196行
return objectMapper.writerWithView(DetailView.class).writeValueAsString(user);
}
private static User getUser() {
User user = new User();
user.setAge("11111");
user.setPassword("pwd");
user.setSex("man");
user.setUserName("name");
return user;
}
public String getAge() {
return age;
}
public User setAge(String age) {
this.age = age;
return this;
}
public String getUserName() {
return userName;
}
public User setUserName(String userName) {
this.userName = userName;
return this;
}
public String getPassword() {
return password;
}
public User setPassword(String password) {
this.password = password;
return this;
}
public String getSex() {
return sex;
}
public User setSex(String sex) {
this.sex = sex;
return this;
}
}
@Test
public void test(){
try {
System.out.println(User.getSimpleView());
System.out.println(User.getDetailView());
} catch (Exception e) {
e.printStackTrace();
}
}
}
{"age":"11111","userName":"name","sex":"man"}
{"age":"11111","userName":"name","password":"pwd","sex":"man"}
-
@JsonView
在springmvc或者springboot中的使用方法:
- springmvc/springboot如果标示为RestController,实际上是在后台了配置MappingJackson2HttpMessageConverter转换器,直接使用就好
- 使用接口来声明多个视图
- 在pojo的get方法上指定视图
- 在Controller方法上指定视图
网友评论