不知道大家日常开发会不会有类似这样的需求,同个API接口不同版本需要返回不同响应值,不同角色需要看到不同响应数据。接到类似这样的需求,一般人的做法可能是针对不同的场景定义不同的DTO,今天给大家介绍一款在springboot项目中可以细粒度控制响应值的大杀器@JsonView
什么是@JsonView?
@JsonView是Spring MVC中使用的Jackson注解,用于在序列化和反序列化过程中控制JSON对象的特定字段。例如,该注释可以允许基于上下文仅返回对象的某些字段。
@JsonView应用场景
注:本示例以springboot web项目来演示,因为springboot的web包本身就含有Jackson包,因此无需引入其他jar
1、定义视图规则接口
public interface AdminJsonView extends PrivateJsonView {
}
public interface UserJsonView extends ProtectedJsonView {
}
public interface PublicJsonView {
}
注: 上述的AdminJsonView、UserJsonView、PrivateJsonView、ProtectedJsonView均继承PublicJsonView,具体可以查看下方demo链接代码
2、定义需要渲染的视图model
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {
@JsonView(PublicJsonView.class)
private String username;
@JsonView(PublicJsonView.class)
private String fullname;
@JsonView(PublicJsonView.class)
private Integer age;
@JsonView({UserJsonView.class,AdminJsonView.class})
private String email;
@JsonView(AdminJsonView.class)
private String phone;
@JsonView(PublicJsonView.class)
private Address address;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Address {
@JsonView({UserJsonView.class, AdminJsonView.class})
private String streetName;
@JsonView(PublicJsonView.class)
private String city;
@JsonView(PublicJsonView.class)
private String country;
@JsonView(AdminJsonView.class)
private String fullAddress;
}
3、定义演示controller
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController {
@GetMapping("public")
@JsonView(PublicJsonView.class)
public User publicUser(){
return UserUtil.generateUser();
}
@GetMapping("default")
@JsonView(UserJsonView.class)
public User defaultUser(){
return UserUtil.generateUser();
}
@GetMapping("admin")
@JsonView(AdminJsonView.class)
public User adminUser(){
return UserUtil.generateUser();
}
}
在每个方法上用@JsonView指定返回对象时使用哪个视图User,然后对3个方法进行测试,通过浏览器访问
1、publicJsonView场景
2、userJsonView场景
3、adminJsonView场景
通过浏览器访问的结果,可以看到不同的视图返回不同的响应值。
因为每个控制器方法只能指定一个@Jsonview注解,因此上述的示例比较适用于API不同版本响应不同值的场景,如果我们想通过一个方法就可以控制不同的响应值输出,我们就可以采用示例二的做法
示例以不同token响应不同视图为例
1、编写维系token与jsonview视图规则的映射绑定
public class UserJsonViewFactory implements JsonViewFactory {
private Map<String,Class<? extends PublicJsonView>> jsonViewClassMap = new ConcurrentHashMap<>();
@Override
public Class<? extends PublicJsonView> getJsonViewClass(HttpServletRequest request,Object... body) {
String token = request.getHeader("token");
if(StringUtils.isEmpty(token)){
return null;
}
return jsonViewClassMap.get(token);
}
@Override
public void initJsonViewClasses() {
jsonViewClassMap.put("123", PublicJsonView.class);
jsonViewClassMap.put("456", UserJsonView.class);
jsonViewClassMap.put("789", AdminJsonView.class);
}
}
2、编写控制器
@RestController
@RequestMapping("user")
@RequiredArgsConstructor
public class UserController {
private final UserJsonViewFactory userJsonViewFactory;
@GetMapping("getUserByToken")
public MappingJacksonValue getUserByToken(HttpServletRequest request){
MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(UserUtil.generateUser());
Class<? extends PublicJsonView> roleViewByToken = userJsonViewFactory.getJsonViewClass(request);
if(roleViewByToken != null){
mappingJacksonValue.setSerializationView(roleViewByToken);
}
return mappingJacksonValue;
}
}
3、测试不同token的响应值情况
[root@master01 ~]# curl http://localhost:8080/user/getUserByToken -H 'token:123'
{"username":"hanzhize","fullname":"韩志泽","age":23,"address":{"city":"汕头","country":"Senegal"}}
[root@master01 ~]# curl http://localhost:8080/user/getUserByToken -H 'token:456'
{"username":"luzhehan","fullname":"卢哲瀚","age":25,"email":"luzhehan@qq.com","address":{"streetName":"韩路","city":"汕尾","country":"Macao"}}
[root@master01 ~]# curl http://localhost:8080/user/getUserByToken -H 'token:789'
{"username":"denghao","fullname":"邓浩","age":2,"email":"denghao@qq.com","phone":"334-44107556","address":{"streetName":"张街","city":"库尔勒","country":"Congo","fullAddress":"Suite 236 龚桥3号, 张家口, 豫 196243"}}
通过测试可以发现不同的token返回不同的响应值,虽然上述实现通过一个方法就可以控制不同的响应值输出,但是实际开发过程中,如果我们是一个已经在运行的项目,业务对象比较多,把原有的业务对象改成mappingJacksonValue,这样改的成本就有点高。因此还有没有更优雅的方式,接下来就看下示例三的做法
示例仍然以不同token响应不同视图为例,维系token与jsonview视图规则的映射绑定同示例二
1、编写ResponseBodyAdvice
@RestControllerAdvice
@Slf4j
public class JsonViewReponseBodyAdvice implements ResponseBodyAdvice<Object>, ApplicationContextAware {
private final ObjectMapper objectMapper;
private final JsonViewProperty jsonViewProperty;
private ApplicationContext applicationContext;
public JsonViewReponseBodyAdvice(JsonViewProperty jsonViewProperty) {
this.jsonViewProperty = jsonViewProperty;
objectMapper = new ObjectMapper();
}
@Override
public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
if(!jsonViewProperty.isEnabled() || returnType.hasMethodAnnotation(JsonView.class) || CollectionUtils.isEmpty(jsonViewProperty.getJsonViewModelClasses())){
return false;
}
return isMatchJsonViewModel(Objects.requireNonNull(returnType.getMethod()).getReturnType());
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
if(body == null){
return null;
}
Class<? extends PublicJsonView> jsonViewClass = getJsonViewClass(body,request);
try {
if(jsonViewClass != null){
objectMapper.setConfig(objectMapper.getSerializationConfig().withView(jsonViewClass));
}
String json = objectMapper.writeValueAsString(body);
return objectMapper.readValue(json,body.getClass());
} catch (Exception e) {
log.error("json序列化异常",e);
}finally {
// 重置ObjectMapper的JsonView配置
objectMapper.setConfig(objectMapper.getSerializationConfig().withView(null));
}
return body;
}
private Class<? extends PublicJsonView> getJsonViewClass(Object body,ServerHttpRequest request) {
if(body == null || !isMatchJsonViewModel(body.getClass())){
return null;
}
JsonViewFactory jsonViewFactory = getJsonViewFactory(body);
ServletServerHttpRequest servletServerHttpRequest = (ServletServerHttpRequest) request;
return jsonViewFactory.getJsonViewClass(servletServerHttpRequest.getServletRequest(),body);
}
private JsonViewFactory getJsonViewFactory(Object body){
if(body == null){
return null;
}
return applicationContext.getBean(body.getClass().getName() + JSON_VIEW_FACTORY_SUFFIX,JsonViewFactory.class);
}
private boolean isMatchJsonViewModel(Class<?> modelClz){
return jsonViewProperty.getJsonViewModelClasses().stream().anyMatch(clazz -> clazz.equals(modelClz));
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
2、编写controller
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping("/get")
public User getUser(){
return UserUtil.generateUser();
}
}
3、在application.yml做如下配置
lybgeek:
jsonview:
enabled: true
ignore-null-property-value: true
json-view-factory-map:
com.github.lybgeek.jsonview.user.model.User: com.github.lybgeek.jsonview.user.roleview.factory.UserJsonViewFactory
注: json-view-factory-map主要是用来维系视图对象bean和生产视图规则工厂的绑定
3、测试不同token的响应值情况
[root@master01 ~]# curl http://localhost:8080/user/get -H 'token:123'
{"username":"zhengminghui","fullname":"郑明辉","age":0,"address":{"city":"唐山","country":"Ghana"}}
[root@master01 ~]# curl http://localhost:8080/user/get -H 'token:456'
{"username":"fengyuze","fullname":"冯雨泽","age":0,"email":"fengyuze@qq.com","address":{"streetName":"贺侬","city":"阳泉","country":"Faroe Islands"}}
[root@master01 ~]# curl http://localhost:8080/user/get -H 'token:789'
{"username":"lu:jinpeng","fullname":"吕晋鹏","age":20,"email":"lu:jinpeng@qq.com","phone":"48000096798","address":{"streetName":"姚路","city":"德州","country":"Colombia","fullAddress":"孙侬95号, 潍坊, 澳 406722"}
通过测试可以发现不同token其响应的视图也是不一样的
@JsonView主要应用于需要根据业务逻辑、安全要求、性能考虑或API设计原则动态调整JSON输出内容的场景,帮助开发者精确控制序列化过程,实现数据暴露的灵活性和安全性。不过这边有几点注意事项
最后Jackson有个@JsonFilter注解也可以实现上述效果,不过它与@JsonView 有所不同,主要适用于更复杂、动态的过滤场景,特别是在需要对对象树中的多个嵌套层级或集合元素进行条件筛选。感兴趣的朋友可以去了解下
https://github.com/lyb-geek/springboot-learning/tree/master/springboot-jsonview
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。