我是靠谱客的博主 生动百合,最近开发中收集的这篇文章主要介绍Jackson动态处理返回字段,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

有时候业务需要动态返回字段,比如,

场景一:返回 name , birthday, createDate

场景二:返回name, birthday, age

现做个备忘录,以便参考。

下面是引入的POM

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>

 

创建 JacksonJson过滤器类,代码如下:


@JsonFilter("JacksonFilter")
public class JacksonJsonFilter extends FilterProvider{

    Map<Class<?>, Set<String>> includeMap = new HashMap<>();
    Map<Class<?>, Set<String>> filterMap = new HashMap<>();

    public void include(Class<?> type, String[] fields) {
        addToMap(includeMap, type, fields);
    }

    public void filter(Class<?> type, String[] fields) {
        addToMap(filterMap, type, fields);
    }
    
    private void addToMap(Map<Class<?>, Set<String>> map, Class<?> type, String[] fields) {
        Set<String> filedSet=new HashSet<>();
        if(fields!=null && fields.length>0){
            for(String filed : fields){
                filedSet.add(filed);
            }
        }
        map.put(type, filedSet);
    }

    @Override
    public BeanPropertyFilter findFilter(Object filterId) {
        throw new UnsupportedOperationException("Access to deprecated filters not supported");
    }

    @Override
    public PropertyFilter findPropertyFilter(Object filterId, Object valueToFilter) {

        return new SimpleBeanPropertyFilter() {

            @Override
            public void serializeAsField(Object pojo, JsonGenerator jgen, SerializerProvider prov, PropertyWriter writer)
                    throws Exception {
                if (apply(pojo.getClass(), writer.getName())) {
                    writer.serializeAsField(pojo, jgen, prov);
                } else if (!jgen.canOmitFields()) {
                    writer.serializeAsOmittedField(pojo, jgen, prov);
                }
            }
        };
    }

    public boolean apply(Class<?> type, String name) {
        Set<String> includeFields = includeMap.get(type);
        Set<String> filterFields = filterMap.get(type);
        if (includeFields != null && includeFields.contains(name)) {
            return true;
        } else if (filterFields != null && !filterFields.contains(name)) {
            return true;
        } else if (includeFields == null && filterFields == null) {
            return true;
        }
        return false;
    }

}

 

写个Util工具类

public class JsonWareUtil {

    private static ObjectMapper objectMapper = null;

    private static JacksonJsonFilter jacksonFilter = new JacksonJsonFilter();
    
    static {
        if(objectMapper==null){
              objectMapper = new ObjectMapper();

        // 允许对象忽略json中不存在的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许出现特殊字符和转义符 objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true); // 允许出现单引号 objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true); // 忽视为空的属性  objectMapper.setSerializationInclusion(Include.NON_EMPTY);

       }

    public static void filter(Class<?> clazz, String include, String filter) {
        if (clazz == null) return; if (StringUtils.isNotBlank(include)) { jacksonFilter.include(clazz, include.split(",")); } if (StringUtils.isNotBlank(filter)) { jacksonFilter.filter(clazz, filter.split(",")); } objectMapper.addMixIn(clazz, jacksonFilter.getClass()); }

 

    /**
     * @param obj 被转对象
     * @return JSON串
     * 将对象转JSON字符串
     */
    public static String beanToJson(Object obj) {
        try {

            objectMapper.setFilterProvider(jacksonFilter);
            String jsonString = objectMapper.writeValueAsString(obj);
            return jsonString;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

 

...

下面省略其他封装的JSON操作方法。

}

 

使用:

public class Test {

     public static void mian(String[] args) {

          // fields: name , birthday, createDate, age

          A a = new A();

          a.setName("test1");
          a.setBirthday("xxxx-xx-xx");

          a.setCreateDate("2019-05-12 12:22:21");

          a.setAge(16);

 

          JsonWareUtil.filter(A.getClass(), "name, birthday", null);

          String json = JsonWareUtil.beanToJson(a);

          System.out.println(json);

     }

}

 

转载于:https://www.cnblogs.com/jimmyshan-study/p/10882507.html

最后

以上就是生动百合为你收集整理的Jackson动态处理返回字段的全部内容,希望文章能够帮你解决Jackson动态处理返回字段所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(60)

评论列表共有 0 条评论

立即
投稿
返回
顶部