首页

通过alibaba的Jackson之objectMapper定义JacksonUtils工具类实现json字符串和对象集合间相互转换

标签:jackson工具类,json字符串,转map,转List,转泛型     发布时间:2021-08-28   

一、前言

基于alibaba的jackson工具库的objectMapper对象实现JSON字符串和常见对象集合容器类型(Map/List/泛型等)相互转换,主要依赖pom如下

<dependency>@b@  <groupId>com.fasterxml.jackson.core</groupId>@b@  <artifactId>jackson-core</artifactId>@b@  <version>2.9.6</version>@b@</dependency>@b@ @b@<dependency>@b@  <groupId>com.fasterxml.jackson.core</groupId>@b@  <artifactId>jackson-annotations</artifactId>@b@  <version>2.9.6</version>@b@</dependency>@b@ @b@<dependency>@b@  <groupId>com.fasterxml.jackson.core</groupId>@b@  <artifactId>jackson-databind</artifactId>@b@  <version>2.9.6</version>@b@</dependency>

二、代码示例

package com.xwood.cloud.jackson;@b@@b@import com.alibaba.excel.util.CollectionUtils;@b@import com.fasterxml.jackson.core.JsonParser;@b@import com.fasterxml.jackson.core.type.TypeReference;@b@import com.fasterxml.jackson.databind.*;@b@import org.apache.commons.lang.StringUtils;@b@import org.springframework.util.ClassUtils;@b@@b@import java.text.SimpleDateFormat;@b@import java.util.*;@b@@b@public class JacksonUtils {@b@@b@    private static ObjectMapper objectMapper = new ObjectMapper();@b@@b@    static {@b@        objectMapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY,true);@b@        //配置true标识mapper接受数组作为object对象反序列化@b@        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);@b@        //反序列化时,遇到未知属性时是否引起结果失败@b@        objectMapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS,false);@b@        //获取getter方法需setter方法,否则@b@@b@        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES,true);@b@        //是否将允许使用非双引号属性名字(这种形式在Javascript中被允许,但是)@b@        objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER,true);@b@        //该特性可以运行接受所有引号引起来的字符,使用‘反斜杠\’机制@b@        objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES,true);@b@        //允许出现单引号@b@        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS,true);@b@        //允许jacksonUtilsON字符串包含非引号控制字符(值小于32的ASCII字符@b@        objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);@b@        //排序@b@        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);@b@        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));@b@        //所有的日期格式都统一为以下的样式,即yyyy-MM-dd HH:mm:ss@b@        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));@b@        //指定默认时区东八区@b@        //忽略空Bean转jacksonUtilson的错误@b@        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS,false);@b@        //类为空时,不要抛异常@b@    }@b@@b@    /**@b@     * 对象转字符串@b@     * @param obj@b@     * @return@b@     */@b@    public static <T> String obj2String(T obj){@b@        if(obj == null){@b@            return null;@b@        }@b@        try {@b@            return obj instanceof String ? (String)obj :  objectMapper.writeValueAsString(obj);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            return null;@b@        }@b@    }@b@@b@    /**@b@     * 有格式的字符串@b@     * @param obj@b@     * @return@b@     */@b@    public static <T> String obj2StringPretty(T obj){@b@        if(obj == null){@b@            return null;@b@        }@b@        try {@b@            return obj instanceof String ? (String)obj :  objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            return null;@b@        }@b@    }@b@@b@    /**@b@     * 字符串转对象@b@     * @param str@b@     * @param clazz@b@     * @return@b@     */@b@    public static <T> T string2Obj(String str,Class<T> clazz){@b@        if(StringUtils.isEmpty(str) || clazz == null){@b@            return null;@b@        }@b@@b@        try {@b@            return clazz.equals(String.class)? (T)str : objectMapper.readValue(str,clazz);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            return null;@b@        }@b@    }@b@@b@    /**@b@     * 字段符转List之类的集合@b@     * @param str@b@     * @param typeReference@b@     * @return@b@     */@b@    public static <T> T string2Obj(String str, TypeReference<T> typeReference){@b@        if(StringUtils.isEmpty(str) || typeReference == null){@b@            return null;@b@        }@b@        try {@b@            return (T)(typeReference.getType().equals(String.class)? str : objectMapper.readValue(str,typeReference));@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            return null;@b@        }@b@    }@b@@b@    /**@b@     * 差不多同上@b@     * @param str@b@     * @param collectionClass@b@     * @param elementClasses@b@     * @return@b@     */@b@    public static <T> T string2Obj(String str,Class<?> collectionClass,Class<?>... elementClasses){@b@        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass,elementClasses);@b@        try {@b@            return objectMapper.readValue(str,javaType);@b@        } catch (Exception e) {@b@            e.printStackTrace();@b@            return null;@b@        }@b@    }@b@@b@    /**@b@     * 字符串转各种类型List@b@     * @param str@b@     * @param clazz@b@     * @param <T>@b@     * @return@b@     */@b@    public  static  <T> List<T> string2List(String str,Class<T> clazz){@b@        if(StringUtils.isEmpty(str)){@b@            return null;@b@        }@b@        if(ClassUtils.isPrimitiveOrWrapper(clazz) || ClassUtils.isAssignable(String.class,clazz)@b@                || ClassUtils.isAssignable(List.class,clazz)@b@                || ClassUtils.isAssignable(Set.class,clazz)@b@                || ClassUtils.isAssignable(Map.class,clazz)){@b@@b@            return  string2Obj(str, new TypeReference<List<T>>() {});@b@        }else{@b@            List<Map<String,Object>>  maplist = (List<Map<String,Object>>)string2Obj(str, new TypeReference<List<T>>() {});@b@            List<T>  result=new ArrayList<>();@b@            for(Map<String,Object> map:maplist){@b@                result.add(map2Obj(map,clazz));@b@            }@b@            return  result;@b@       }@b@@b@    }@b@@b@    /**@b@     * 字符串json转Map@b@     * @param jsonStr@b@     * @param <T>@b@     * @return@b@     */@b@    public static <T> Map<String,Object> string2Map(String jsonStr){@b@        try {@b@            if(jsonStr==null){@b@                return null;@b@            }@b@            return  objectMapper.readValue(jsonStr,Map.class);@b@        } catch(Exception e) {@b@        }@b@        return null;@b@    }@b@@b@    /**@b@     * 字符串json转Map@b@     * @param jsonStr@b@     * @param clazz@b@     * @param <T>@b@     * @return@b@     */@b@    public static <T> Map<String, T> string2Map(String jsonStr,Class<T> clazz){@b@        try {@b@            if(jsonStr==null){@b@                return null;@b@            }@b@@b@            Map<String,Map<String,Object>>  map=objectMapper.readValue(jsonStr,new TypeReference<Map<String,T>>(){@b@@b@            });@b@@b@            if(CollectionUtils.isEmpty(map)){@b@                return  Collections.emptyMap();@b@            }else{@b@                Map<String,T> result=new HashMap<>(map.size());@b@                for(Map.Entry<String,Map<String,Object>>  entry:map.entrySet()){@b@                    result.put(entry.getKey(),map2Obj(entry.getValue(),clazz));@b@                }@b@                return result;@b@            }@b@@b@        } catch(Exception e) {@b@        }@b@         return null;@b@    }@b@@b@    /**@b@     * map转dto对象@b@     * @param map@b@     * @param clazz@b@     * @param <T>@b@     * @return@b@     */@b@    public static <T>  T  map2Obj(Map map, Class<T> clazz){@b@        return  objectMapper.convertValue(map,clazz);@b@    }@b@@b@    public static void main(String[] args) {@b@@b@@b@        User user1 = new User(1L,"ywj", 123, new Date());@b@        //1.对象转字符串@b@        System.out.println("【1】:"+JacksonUtils.obj2String(user1));@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //2.对象转有个格式的字符串@b@        System.out.println("【2】:"+JacksonUtils.obj2StringPretty(user1));@b@        System.out.println("_____________________________________________\n\r");@b@@b@        // 3.字符串转对象,打印name字段@b@        User user2 = JacksonUtils.string2Obj("{\"id\":1,\"name\":\"ywj\",\"age\":123,\"date\":\"2018-01-14 22:14:18\",\"abc\":\"abc\"}", User.class);@b@        System.out.println("【3】:"+user2.getName());@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //4.将List转字符串@b@        List<User> userList = new ArrayList<User>();@b@        userList.add(new User(1L,"ywj", 123, new Date()));@b@        userList.add(new User(2L,"ywj2", 123, new Date()));@b@        //转字符串@b@        String userListString = JacksonUtils.obj2String(userList);@b@        System.out.println("【4】:"+userListString);@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //5.字符串转List - TypeReference方式@b@        String userListString2=userListString;@b@        List<User> userList2 = JacksonUtils.string2Obj(userListString2, new TypeReference<List<User>>() {});@b@        System.out.println("【5】:"+userList2.size()+":"+userList2.get(1).getName());@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //6.字符串转List 2@b@        String userListString3=userListString;@b@        List<User> userList3 = JacksonUtils.string2Obj(userListString3, List.class, User.class);@b@        System.out.println("【6】:"+userList3.size()+":"+userList3.get(1).getName());@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //7.字符串转List 3@b@        String userListString4=userListString;@b@        List<User> userList4 = JacksonUtils.string2List(userListString4, User.class);@b@        System.out.println("【7】:"+userList4.size()+":"+userList4.get(1).getName());@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //8.字符串转Map@b@        String userListString5=JacksonUtils.obj2String(user1);@b@        Map<String,Object> userMap=JacksonUtils.string2Map(userListString5);@b@        System.out.println("【8】:"+userMap);@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //9.字符串转Map 2@b@        String userListString6=JacksonUtils.obj2String(user1);;@b@        Map<String,?> userMap2=JacksonUtils.string2Map(userListString5,String.class);@b@        System.out.println("【9】:"+userMap2);@b@        System.out.println("_____________________________________________\n\r");@b@@b@        //10. map转User@b@        Map<String,Object> userMap3=userMap;@b@        User user4=JacksonUtils.map2Obj(userMap3,User.class);@b@        System.out.println("【10】:"+user4.getName());@b@@b@@b@    }@b@@b@@b@}

控制台运行结果

【1】:{"abc":null,"age":123,"date":"2021-08-28 01:57:56","id":1,"name":"ywj"}@b@_____________________________________________@b@@b@【2】:{@b@  "abc" : null,@b@  "age" : 123,@b@  "date" : "2021-08-28 01:57:56",@b@  "id" : 1,@b@  "name" : "ywj"@b@}@b@_____________________________________________@b@@b@【3】:ywj@b@_____________________________________________@b@@b@【4】:[{"abc":null,"age":123,"date":"2021-08-28 01:57:56","id":1,"name":"ywj"},{"abc":null,"age":123,"date":"2021-08-28 01:57:56","id":2,"name":"ywj2"}]@b@_____________________________________________@b@@b@【5】:2:ywj2@b@_____________________________________________@b@@b@【6】:2:ywj2@b@_____________________________________________@b@@b@【7】:2:ywj2@b@_____________________________________________@b@@b@【8】:{abc=null, age=123, date=2021-08-28 01:57:56, id=1, name=ywj}@b@_____________________________________________@b@@b@【9】:null@b@_____________________________________________@b@@b@【10】:ywj@b@@b@Process finished with exit code 0
<<热门下载>>