fastjson自由:controller上指定active profile,让你想序列化什么字段就序列化什么字段
2019-11-11 16:30
阅读目录
2、在profile要应用到的class类型中,在field上添加注解
3、请求接口,返回的结果,如下:
4、如果注释掉注解那两行,则效果如下:
针对仅需要包含部分字段,希望能达到下面的效果:
1、在controller上指定profile
/** * 测试include类型的profile,这里指定了: * 激活profile为 includeProfile * User中,对应的field将会被序列化,其他字段都不会被序列化 */ @GetMapping("/test.do") @ActiveFastJsonProfileInController(profile = "includeProfile",clazz = User.class) public CommonMessage<User> test() { User user = new User(); user.setId(111L); user.setAge(8); user.setUserName("kkk"); user.setHeight(165); CommonMessage<User> message = new CommonMessage<>(); message.setCode("0000"); message.setDesc("成功"); message.setData(user); return message; }
2、在
ActiveFastJsonProfileInController
注解的clazz指定的类中,对需要序列化的字段进行注解:@Data public class User { @FastJsonFieldProfile(profiles = {"includeProfile"},profileType = FastJsonFieldProfileType.INCLUDE) private Long id; private String userName; private Integer age; @FastJsonFieldProfile(profiles = {"includeProfile"},profileType = FastJsonFieldProfileType.INCLUDE) private Integer height; }
3、请求结果如下:
{ code: "0000", data: { id: 111, height: 165 }, desc: "成功" }
- 添加
controllerAdvice
,实现org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice
接口,对返回的responseBody
进行处理- 在
controllerAdvice
中,获取请求路径,然后根据请求路径,去第二步的map中,查询激活的profile和class信息- 根据第四步获取到的:激活的profile和class信息,计算出对应的field集合,比如,根据profile拿到一个字段集合:{name,age},而这两个字段都是 exclude 类型的,所以不能对着两个字段进行序列化
- 根据第五步的field集合,对
responseBody
对象进行处理,不对排除集合中的字段序列化这么讲起来,还是比较抽象,具体可以看第一章的效果截图。
三、实现细节
- 添加