青岛软件培训
  • 首页 (current)
  • 培训课程
  • 开班公告
  • 万码励志
  • 技术文章
  • 万码人
  • 行业新闻
  • 培训问答
  • 学习笔记
  • 留言

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对象进行处理,不对排除集合中的字段序列化
  • 这么讲起来,还是比较抽象,具体可以看第一章的效果截图。

    回到顶部

    三、实现细节

青岛软件培训

选择一家好的青岛软件培训学校,就要看教学质量和口碑

万码学堂-做最负责任的教育-联系电话0532-85025005

鲁ICP备09077726号-3