您当前的位置: 首页 >  json

梁云亮

暂无认证

  • 2浏览

    0关注

    1211博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【精品】基于Jackson的JSON工具类(完美处理日期类型)

梁云亮 发布时间:2020-05-02 17:51:03 ,浏览量:2

Maven依赖

    com.fasterxml.jackson.core
    jackson-databind
    2.13.2.2


    com.fasterxml.jackson.core
    jackson-core
    2.13.2


    com.fasterxml.jackson.core
    jackson-annotations
    2.13.2


    com.fasterxml.jackson.datatype
    jackson-datatype-jsr310
    2.13.0

工具类
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 
     * @return
     */
    public static  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 
     * @return
     */
    public static  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 
     * @return
     */
    public static  T string2Obj(String str, Class 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 
     * @return
     */
    public static  T string2Obj(String str, TypeReference 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 
     * @return
     */
    public static  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 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 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{\t\t\"area\":\"aaaaaa\",\t\t\"name\":\"aa\",\t\t\"id\":1001,\t\t\"priority\":11\t},\t{\t\t\"area\":\"bbbbbb\",\t\t\"name\":\"bb\",\t\t\"id\":1002,\t\t\"priority\":22\t},\t{\t\t\"area\":\"cccccc\",\t\t\"name\":\"cc\",\t\t\"id\":1003,\t\t\"priority\":33\t},\t{\t\t\"area\":\"dddddd\",\t\t\"name\":\"dd\",\t\t\"id\":1004,\t\t\"priority\":44\t}]";
    List provinces = string2Obj(provinceListJson, new TypeReference() {
    });
    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 list = new ArrayList();
        list.add("aaa");
        list.add("bbb");
        list.add("ccc");
        String res1 = JsonUtil.obj2String(list);
        System.out.println(res1);

        ArrayList 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 list1 = JsonUtil.string2Obj(json1,new TypeReference() {});
        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 list2 = JsonUtil.string2Obj(json2,new TypeReference() {});
        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 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,否则会报错: 在这里插入图片描述

关注
打赏
1665409997
查看更多评论
立即登录/注册

微信扫码登录

0.2927s