我是靠谱客的博主 大意雪碧,最近开发中收集的这篇文章主要介绍【精品】基于Jackson的JSON工具类(完美处理日期类型)Maven依赖工具类测试代码测试代码二,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

Maven依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.13.2.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.13.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-annotations</artifactId>
    <version>2.13.2</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.13.0</version>
</dependency>

工具类

package com.wego.common.web.utils;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

/**
 * @author hc
 * Json工具类
 * 亮点:模拟构造方法设计模式提供类似于阿里巴巴FastJSON的put方式构造JSON字符串的功能
 */
public class JsonUtil {

    private static ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 默认日期时间格式
     */
    private static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";

    /**
     * 默认日期格式
     */
    private static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 默认时间格式
     */
    private static final String TIME_FORMAT = "HH:mm:ss";


    /**
     * Json序列化和反序列化转换器
     */
    static {
        //java8日期 Local系列序列化和反序列化模块
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        //序列化
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));
        //反序列化
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT)));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT)));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATE_TIME_FORMAT)));

        objectMapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(javaTimeModule);

        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
        // 忽略json字符串中不识别的属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 忽略无法转换的对象
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        // PrettyPrinter 格式化输出
        objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
        // NULL不参与序列化
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 指定时区
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        /**
         * Date日期类型字符串全局处理, 默认格式为:yyyy-MM-dd HH:mm:ss
         * 局部处理某个Date属性字段接收或返回日期格式yyyy-MM-dd, 可采用@JsonFormat(pattern = "yyyy-MM-dd", timezone="GMT+8")注解标注该属性
         */
        objectMapper.setDateFormat(new SimpleDateFormat(DATE_TIME_FORMAT));
    }

    /**
     * 将对象转换成字符串
     * @param obj
     * @param <T>
     * @return
     */
    public static <T> String obj2String(T obj) {
        if (obj == null) {
            return null;
        }
        String s = null;
        try {
            s = obj instanceof String ? (String) obj : objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * 将对象转换成格式化后的字符串
     * @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 (JsonProcessingException e) {
            return null;
        }
    }

    /**
     * 字符串转对象
     * @param str
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, Class<T> clazz) {
        if (str == null || str.length() == 0 || clazz == null) {
            return null;
        }
        T t = null;
        try {
            t = clazz.equals(String.class) ? (T) str : objectMapper.readValue(str, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 在字符串与集合对象转换时使用
     * @param str
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, TypeReference<T> typeReference) {
        if (str == null || str.length() == 0 || typeReference == null) {
            return null;
        }
        try {
            return (T) (typeReference.getType().equals(String.class) ? str : objectMapper.readValue(str, typeReference));
        } catch (IOException e) {
            return null;
        }
    }

    /**
     * 在字符串与集合对象转换时使用
     * @param str
     * @param collectionClazz
     * @param elementClazzes
     * @param <T>
     * @return
     */
    public static <T> T string2Obj(String str, Class<?> collectionClazz, Class<?>... elementClazzes) {
        JavaType javaType = objectMapper.getTypeFactory().constructParametricType(collectionClazz, elementClazzes);
        try {
            return objectMapper.readValue(str, javaType);
        } catch (IOException e) {
            return null;
        }
    }


    public static JsonBuilder builder() {
        return new JsonBuilder();
    }

    public static class JsonBuilder {
        private Map<String, Object> map = new HashMap<>();

        private JsonBuilder() {
        }

        public JsonBuilder put(String key, Object value) {
            map.put(key, value);
            return this;
        }

        public String build() {
            try {
                return objectMapper.writeValueAsString(this.map);
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return "{}";
        }
    }

}



测试代码

待测试的类

  • Province
@Data
@AllArgsConstructor
class Province {
    private Long id;
    private String name;
    private String area;
    private Integer priority;
}
  • AA
@Data
@AllArgsConstructor
class AA {
    private Date date;
    private LocalTime localTime;
    private LocalDate localDate;
    private LocalDateTime localDateTime;
}

测试代码

public static void main(String[] args) {
    AA aa = new AA(new Date(), LocalTime.now(), LocalDate.now(), LocalDateTime.now());

    String obj2String = obj2String(aa);
    System.out.println(obj2String);

    String obj2StringPretty = obj2StringPretty(aa);
    System.out.println(obj2StringPretty);

    String str = "{  "date" : "2022-09-30 09:04:14",  "localTime" : "09:04:14",  "localDate" : "2022-09-30",  "localDateTime" : "2022-09-30 09:04:14"}";
    AA obj = string2Obj(str, AA.class);
    System.out.println(obj);

    String json = JsonUtil.builder()
            .put("localTime", LocalTime.now())
            .put("localDate", LocalTime.now())
            .put("name", "test")
            .put("localDateTime", LocalDateTime.now())
            .build();
    System.out.println(json);

    List<Province> provinceList = new ArrayList<>();
    provinceList.add(new Province(1001L, "aa", "aaaaaa", 11));
    provinceList.add(new Province(1002L, "bb", "bbbbbb", 22));
    provinceList.add(new Province(1003L, "cc", "cccccc", 33));
    provinceList.add(new Province(1004L, "dd", "dddddd", 44));

    String provinceListJson = obj2String(provinceList);
    System.out.println(provinceListJson);

    provinceListJson = "[t{tt"area":"aaaaaa",tt"name":"aa",tt"id":1001,tt"priority":11t},t{tt"area":"bbbbbb",tt"name":"bb",tt"id":1002,tt"priority":22t},t{tt"area":"cccccc",tt"name":"cc",tt"id":1003,tt"priority":33t},t{tt"area":"dddddd",tt"name":"dd",tt"id":1004,tt"priority":44t}]";
    List<Province> provinces = string2Obj(provinceListJson, new TypeReference<List<Province>>() {
    });
    provinces.forEach(System.out::println);

    System.out.println();

    provinces = string2Obj(provinceListJson, List.class, Province.class);
    provinces.forEach(System.out::println);

}

测试代码二

class JsonUtilTest {

    @Test
    void obj2String() {
        Dept dept = new Dept(10, "SALES", "CHICAGO");
        String res = JsonUtil.obj2String(dept);
        System.out.println(res);

        List<String> list = new ArrayList<>();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        String res1 = JsonUtil.obj2String(list);
        System.out.println(res1);

        ArrayList<Dept> depts = new ArrayList<>();
        depts.add(new Dept(10,"ACCOUNTING","NEWYORK"));
        depts.add(new Dept(20,"RESEARCH","DALLAS"));
        depts.add(new Dept(30,"SALES","CHICAGO"));
        depts.add(new Dept(40,"OPERATIONS","BOSTON"));
        String res2 = JsonUtil.obj2String(depts);
        System.out.println(res2);
    }

    @Test
    void obj2StringPretty() {
        Dept dept = new Dept(10, "SALES", "CHICAGO");
        String res = JsonUtil.obj2StringPretty(dept);
        System.out.println(res);
    }

    @Test
    void string2Obj() {
        String json = "{"deptno":10,"dname":"SALES","loc":"CHICAGO"}";
        Dept dept = JsonUtil.string2Obj(json, Dept.class);
        System.out.println(dept.getDname());
    }

    @Test
    void testString2Obj() {
        String json1="["aaa","bbb","ccc"]";
        List<String> list1 = JsonUtil.string2Obj(json1,new TypeReference<List<String>>() {});
        System.out.println(list1.get(1));

        String json2 ="[{"deptno":10,"dname":"ACCOUNTING","loc":"NEWYORK"},{"deptno":20,"dname":"RESEARCH","loc":"DALLAS"},{"deptno":30,"dname":"SALES","loc":"CHICAGO"},{"deptno":40,"dname":"OPERATIONS","loc":"BOSTON"}]";
        List<Dept> list2 = JsonUtil.string2Obj(json2,new TypeReference<List<Dept>>() {});
        System.out.println(list2.get(2).getDname());
    }

    @Test
    void testString2Obj1() {
        String json ="[{"deptno":10,"dname":"ACCOUNTING","loc":"NEWYORK"},{"deptno":20,"dname":"RESEARCH","loc":"DALLAS"},{"deptno":30,"dname":"SALES","loc":"CHICAGO"},{"deptno":40,"dname":"OPERATIONS","loc":"BOSTON"}]";
        List<Dept> list = JsonUtil.string2Obj(json,List.class,Dept.class);
        System.out.println(list.get(2));
    }

    @Test
    void builder() {
        String json = JsonUtil.builder()
                .put("id", 123)
                .put("name", "zhangsan")
                .put("birth", LocalDate.now())
                .put("gender", true)
                .build();
        System.out.println(json);
    }

}

备注

上面工具类需要注入jackson-datatype-jsr310,否则会报错:
在这里插入图片描述

最后

以上就是大意雪碧为你收集整理的【精品】基于Jackson的JSON工具类(完美处理日期类型)Maven依赖工具类测试代码测试代码二的全部内容,希望文章能够帮你解决【精品】基于Jackson的JSON工具类(完美处理日期类型)Maven依赖工具类测试代码测试代码二所遇到的程序开发问题。

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

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

评论列表共有 0 条评论

立即
投稿
返回
顶部