zoukankan      html  css  js  c++  java
  • 自定义JSON返回字段

    今天看到一篇文章,里面介绍了如何自定义返回json字段,感觉挺好用的,这里学习一下。

    实现工具类:

    /**
     * @author fengzp
     * @date 17/2/20上午10:34
     * @email fengzp@gzyitop.com
     * @company 广州易站通计算机科技有限公司
     */
    public class JsonFilter {
    
        private static final String INCLUDE = "JSON_INCLUDE";
        private static final String EXCEPT = "JSON_EXCEPT";
    
        @com.fasterxml.jackson.annotation.JsonFilter(INCLUDE)
        interface MyJsonInclude {}
    
        @com.fasterxml.jackson.annotation.JsonFilter(EXCEPT)
        interface MyJsonExcept {}
    
    
        public static String mapper(Object bean, Class<?> clazz, String include, String except) throws JsonProcessingException {
    
            if(clazz == null)
                return null;
    
            ObjectMapper mapper = new ObjectMapper();
    
            if(StringUtils.hasText(include)){
                mapper.setFilterProvider(new SimpleFilterProvider().addFilter(INCLUDE,
                        SimpleBeanPropertyFilter.filterOutAllExcept(include.split(","))));
    
                mapper.addMixIn(clazz, MyJsonInclude.class);
            }
    
            if(StringUtils.hasText(except)){
                mapper.setFilterProvider(new SimpleFilterProvider().addFilter(EXCEPT,
                        SimpleBeanPropertyFilter.serializeAllExcept(except.split(","))));
    
                mapper.addMixIn(clazz, MyJsonExcept.class);
            }
    
            return mapper.writeValueAsString(bean);
        }
    
    }
    

    测试:

    public class User {
    private Integer id;
    
    private String userName;
    
    private String password;
    
    private String realName;
    
    private Boolean status;
    
    private String email;
    
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createdAt;
    
    @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date updatedAt;
    

  • 相关阅读:
    注意力机制在CV领域的应用之SEnet
    知识蒸馏技术原理
    batchsize如何影响模型的性能
    docker网络 macvlan
    docker pull使用 代理
    auditd重启失败
    3.Golang的包导入
    2.golang应用目录结构和GOPATH概念
    使用git版本管理时的免密问题
    1.go语言目录结构
  • 原文地址:https://www.cnblogs.com/andyfengzp/p/6418569.html
Copyright © 2011-2022 走看看