报错:Java 8 date/time type `java.time.LocalDateTime` not supported by default:

本文介绍了如何在Java8中处理Jackson库对`java.time`包(如LocalDateTime,LocalDate,LocalTime)的支持问题,包括添加时间模块、全局配置日期/时间格式以及使用JsonUtils工具类进行序列化和反序列化的操作。
摘要由CSDN通过智能技术生成

项目报错:Java 8 date/time type java.time.LocalDateTime not supported by default:

1.1 原因:jackson默认不支持java8的时间类型,需要添加一个时间模块

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version>2.13.0</version>
</dependency>

1.2 1.2 全局配置一下

package com.xx.xf.conf;

import cn.hutool.core.date.DatePattern;
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.xx.xf.utils.Constants;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;


@Configuration
public class LocalDateFormatConfig {


    /**
     * Date格式化字符串
     */
    private static final String DATE_FORMAT = DatePattern.NORM_DATE_PATTERN; //yyyy-MM-dd
    /**
     * DateTime格式化字符串
     */
    private static final String DATETIME_FORMAT = DatePattern.NORM_DATETIME_PATTERN; //yyyy-MM-dd HH:mm:ss
    /**
     * Time格式化字符串
     */
    private static final String TIME_FORMAT = Constants.Time.TIME_FORMAT; //HH:mm

    @Bean
    @Primary
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT, Locale.CHINA)))
                .serializerByType(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DATE_FORMAT, Locale.CHINA)))
                .serializerByType(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(TIME_FORMAT, Locale.CHINA)))
                .deserializerByType(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DATETIME_FORMAT, Locale.CHINA)))
                .deserializerByType(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DATE_FORMAT, Locale.CHINA)))
                .deserializerByType(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(TIME_FORMAT, Locale.CHINA)));
    }

}

在代码中序列化和反序列化时,需要用到工具类,并且在使用ObjectMapper
的时候注册JavaTimeModule这个模块。

ObjectMapper objectMapper = new ObjectMapper();
 
//现在需要在中间加一个
objectMapper.registerModule(new JavaTimeModule());
 
String s = objectMapper.writeValueAsString(VOList);

因此,再次修改,为了方便起见,我们添加一个工具类JsonUtils

package com.xx.xf.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.xx.xf.entity.MimoSensorData;
import com.xx.xf.exception.JSONToStringException;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;


public class JsonUtils {

    public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
    static {
        OBJECT_MAPPER.registerModule(new JavaTimeModule());
    }

    public static String toJSONString(Object value) {
        try {
            return OBJECT_MAPPER.writeValueAsString(value);
        } catch (JsonProcessingException e) {
            throw new JSONToStringException(e.getMessage());
        }
    }

    public static <T> List<T> parseArray(String conditionString, TypeReference<List<T>> valueTypeRef) {
        try {
            List<T> deviceControlConditions = OBJECT_MAPPER.readValue(conditionString, valueTypeRef);

            return deviceControlConditions;
        } catch (JsonProcessingException e) {
            throw new JSONToStringException(e.getMessage());
        }
    }
    public static <T> List<T> parseArrayByType(String conditionString, Class<T> t) {
        try {
            List<T> deviceControlConditions = OBJECT_MAPPER.readValue(conditionString, new TypeReference<List<T>>() {
            });

            return deviceControlConditions;
        } catch (JsonProcessingException e) {
            throw new JSONToStringException(e.getMessage());
        }
    }

    public static JsonNode readTree(String conditionString) {
        try {
            JsonNode jsonNode = OBJECT_MAPPER.readTree(conditionString);
            return jsonNode;
        } catch (JsonProcessingException e) {
            throw new JSONToStringException(e.getMessage());
        }
    }

    public  static <T> T parseObject(String str, Class<T> tClass) {
        try {
            return OBJECT_MAPPER.readValue(str, tClass);
        } catch (JsonProcessingException e) {
            throw new JSONToStringException(e.getMessage());
        }
    }
}

对于需要序列化和反序列化的时候,直接使用该工具类即可。

    public static void main(String[] args) {

        List<LocalDateTime> localDateTimeList = new ArrayList<>();
        LocalDateTime now = LocalDateTime.now();
        localDateTimeList.add(now);
        localDateTimeList.add(now.plusHours(-5));
        localDateTimeList.add(now.plusHours(-6));
        String localDateTimeListStr = JsonUtils.toJSONString(localDateTimeList);
        System.out.println("localDateTimeListStr = " + localDateTimeListStr);

        List<LocalDateTime> conditions = JsonUtils.parseArray(localDateTimeListStr, new TypeReference<List<LocalDateTime>>() {
        });

        for (LocalDateTime condition : conditions) {
            System.out.println("condition = " + condition);
        }
    }

输出结果:

localDateTimeListStr = ["2024-03-21 17:51:28","2024-03-21 12:51:28","2024-03-21 11:51:28"]
condition = 2024-03-21T17:51:28
condition = 2024-03-21T12:51:28
condition = 2024-03-21T11:51:28
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值