• jackson快速实现对象与json之间的转换


    Maven依赖:

    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-avro</artifactId>
        <version>2.9.0</version>
    </dependency>
    <!-- 如果使用@Slf4j 注解,需要引入lombok依赖 -->
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.18</version>
    </dependency>

    工具栏实现:

    @Slf4j
    public class JsonUtil {
        public static ObjectMapper objectMapper = new ObjectMapper();
    
        static {
            //***********************序列化****************************
            //对象的所有字段全部列入
            objectMapper.setSerializationInclusion(Inclusion.ALWAYS);
    
            //取消默认转换timestamps
            objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
    
            //忽略空Bean转json的错误
            objectMapper.configure(SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS, false);
    
            //同意日期格式为:"yyyy-MM-dd HH:mm:ss"
            objectMapper.setDateFormat(new SimpleDateFormat(DateTimeUtil.STANDARD_FORMAT));
            //***********************序列化****************************
    
            //***********************反序列化****************************
            //忽略 在json字符串中存在,但是java对象中不存在对应属性的情况,防止错误。
            objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
            //***********************反序列化****************************
        }
    
        /**
         * Object转json字符串
         *
         * @param obj
         * @param <T>
         * @return
         */
        public static <T> String obj2String(T obj) {
            if (obj == null) {
                return null;
            }
            try {
                return obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
            } catch (Exception e) {
                log.warn("Parse object to String error", e);
                return null;
            }
        }
    
        /**
         * Object转json字符串 将转换的json结果格式化
         *
         * @param obj
         * @param <T>
         * @return
         */
        public static <T> String obj2StringPretty(T obj) {
            if (obj == null) {
                return null;
            }
            try {
                return obj instanceof String ? (String) obj : objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj);
            } catch (Exception e) {
                log.warn("Parse object to String error", e);
                return null;
            }
        }
    
        /**
         * String转Object
         *
         * @param str
         * @param clazz Object类型
         * @param <T>
         * @return
         */
        public static <T> T string2Obj(String str, Class<T> clazz) {
            if (StringUtil.isEmpty(str) || clazz == null) {
                return null;
            }
            try {
                return clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
            } catch (Exception e) {
                log.warn("Parse String to object error", e);
                return null;
            }
        }
    
        /**
         * String转Object 适用于多泛型 eg: 将String转换成 Map<UserClass,CourseClass>
         *
         * @param str
         * @param typeReference  Map<Class1,Class2>
         * @param <T>
         * @return TypeReference 导入包:import org.codehaus.jackson.type.TypeReference;
         */
        public static <T> T string2Obj(String str, TypeReference<T> typeReference) {
            if (StringUtil.isEmpty(str) || typeReference == null) {
                return null;
            }
            try {
                return (T) (typeReference.getType().equals(String.class) ? (T) str : objectMapper.readValue(str, typeReference));
            } catch (Exception e) {
                log.warn("Parse String to object error", e);
                return null;
            }
        }
    
        /**
         * String转Object 使用存在Collection集合 eg:将String转换成List<UserClass>
         *
         * @param str
         * @param collectionClass 集合类型
         * @param elementClasses 集合中对象类型,多个对象类型时传入数组
         * @param <T>
         * @return
         */
        public static <T> T string2Obj(String str, Class<?> collectionClass, Class<?>... elementClasses) {
            JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
            try {
                return objectMapper.readValue(str, javaType);
            } catch (Exception e) {
                log.warn("Parse String to object error", e);
                return null;
            }
        }
    
    }

     

  • 相关阅读:
    JeeSite4.x 搭建并部署到服务器
    maven编译时出现There are test failures
    ecplise An incompatible version [1.2.14] of the APR based Apache Tomcat Native library is installed, while T
    maven "mvn不是内部或外部命令,也不是可运行的程序或批处理文件"
    rar自动压缩备份
    mysql 0x80004005 unable to connect to any of the specified mysql hosts
    mysql too many connections
    输出控制台信息到日志 并 通过cronolog对tomcat进行日志切分
    Node.js相关——package概念及NPM
    Node.js相关——CommonJS规范
  • 原文地址:https://www.cnblogs.com/nowl/p/9959689.html
Copyright © 2020-2023  润新知