首页 > 编程语言 >日期格式转换异常:Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module \&quo

日期格式转换异常:Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module \&quo

时间:2023-10-11 14:35:22浏览次数:36  
标签:jackson java datatype supportMediaTypeList MediaType add time import com

异常信息:

"unexpected error: Type definition error: [simple type, class java.time.LocalDateTime]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310\" to enable handling (through reference chain: com.response.PagableApiResponse[\"data\"]->java.util.ArrayList[0]->com.response.OrderTypesResponse[\"startActiveDate\"])";

解决方案:

(1)自定义组件:LocalDateTimeToTimestampSerializer


import cn.hutool.core.date.DatePattern;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Component
public class LocalDateTimeToTimestampSerializer implements ObjectSerializer {

    public static final LocalDateTimeToTimestampSerializer instance = new LocalDateTimeToTimestampSerializer();
    private static final String defaultPattern = DatePattern.NORM_DATETIME_PATTERN;

    public LocalDateTimeToTimestampSerializer() {
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        SerializeWriter out = serializer.out;
        if (object == null) {
            out.writeNull();
        } else {
            LocalDateTime result = (LocalDateTime) object;
            // 转换为yyyy-MM-dd HH:mm:ss格式
            out.writeString(result.format(DateTimeFormatter.ofPattern(defaultPattern)));
        }
    }

}

(2)自定义配置类:WebMvcConfig 实现 WebMvcConfigurer

import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

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

/**
 * @version 1.0
 * @description:
 * @date 2023-04-26 13:52
 */
@Configuration
@Order(-1)
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/swagger-ui/**")
                .addResourceLocations("classpath:/META-INF/resources/webjars/springfox-swagger-ui/")
                .resourceChain(false);
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/swagger-ui/").setViewName("/swagger-ui/index.html");
    }

    /**
     * JSON-转换器
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters){
        converters.removeIf(MappingJackson2HttpMessageConverter.class::isInstance);

        SerializeConfig serializeConfig = SerializeConfig.globalInstance;
        // 注入自定义LocalDateTime处理器
        serializeConfig.put(LocalDateTime.class, LocalDateTimeToTimestampSerializer.instance);

        FastJsonConfig config = new FastJsonConfig();
        config.setSerializeConfig(serializeConfig);
        config.setSerializerFeatures(SerializerFeature.PrettyFormat);

        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        fastJsonHttpMessageConverter.setSupportedMediaTypes(getSupportMediaTypes());
        fastJsonHttpMessageConverter.setFastJsonConfig(config);

        converters.add(fastJsonHttpMessageConverter);
    }

    /**
     * 配置MediaType
     * @return List<MediaType>
     */
    public static List<MediaType> getSupportMediaTypes() {
        List<MediaType> supportMediaTypeList = new ArrayList<>();
        supportMediaTypeList.add(MediaType.APPLICATION_JSON);
        supportMediaTypeList.add(MediaType.APPLICATION_ATOM_XML);
        supportMediaTypeList.add(MediaType.APPLICATION_FORM_URLENCODED);
        supportMediaTypeList.add(MediaType.APPLICATION_OCTET_STREAM);
        supportMediaTypeList.add(MediaType.APPLICATION_PDF);
        supportMediaTypeList.add(MediaType.APPLICATION_RSS_XML);
        supportMediaTypeList.add(MediaType.APPLICATION_XHTML_XML);
        supportMediaTypeList.add(MediaType.APPLICATION_XML);
        supportMediaTypeList.add(MediaType.IMAGE_GIF);
        supportMediaTypeList.add(MediaType.IMAGE_JPEG);
        supportMediaTypeList.add(MediaType.IMAGE_PNG);
        supportMediaTypeList.add(MediaType.TEXT_EVENT_STREAM);
        supportMediaTypeList.add(MediaType.TEXT_HTML);
        supportMediaTypeList.add(MediaType.TEXT_MARKDOWN);
        supportMediaTypeList.add(MediaType.TEXT_PLAIN);
        supportMediaTypeList.add(MediaType.TEXT_XML);
        return supportMediaTypeList;
    }
}

 

标签:jackson,java,datatype,supportMediaTypeList,MediaType,add,time,import,com
From: https://www.cnblogs.com/huangdh/p/17748446.html

相关文章

  • 《Mastering the FreeRTOS Real Time Kernel》读书笔记(1)堆内存管理
    这是161204的版本,不完全覆盖目前最新版本的内核。0.关于freeRTOS首先提出了了在小型嵌入式系统中为何需要多任务管理的问题,介绍了freeRTOS的用途。然后开始做广告,吹了一波freeRTOS的好处。其中要注意一些关键的名词:任务优先级分配、任务通知、队列、信号量、互斥锁、软定时器、......
  • Jackson--FastJson--XStream--代码执行&&反序列化
    Jackson--FastJson--XStream--代码执行&&反序列化Jackson代码执行(CVE-2020-8840)影响范围2.0.0<=FasterXMLjackson-databindVersion<=2.9.10.2不受影响版本FasterXMLjackson-databind=2.8.11.5FasterXMLjackson-databind=2.9.10.3漏洞利用POC:Stringjson......
  • pydantic学习与使用-17.使用 json_encoders 格式化 datetime 类型
    前言使用datetime日期类型时,想格式化成自定义的"%Y-%m-%d%H:%M:%S"格式datetime类型frompydanticimportBaseModelfromdatetimeimportdatetime#上海悠悠wx:283340479#blog:https://www.cnblogs.com/yoyoketang/classUserInfo(BaseModel):id:intna......
  • Android Studio可以编译但Flutter提示无法定位java runtime
    AndroidStudio可以编译但Flutter提示无法定位javaruntime下面我们重点讲一下“UnabletofindbundledJavaversion”报错问题到AndroidStudio安装目录下注意:有些AndroidStudio可能是“jbr”文件,不用管jbr文件,直接复制一份jbr文件在同一路经,再把复制的文件改名为“jre”文......
  • Time Series Forecasting Methods
    基于EEMD-Prophet-LSTM的滑坡位移预测LSTM与Prophet时间序列预测实验11ClassicalTimeSeriesForecastingMethodsinMATLAB-FileExchange-MATLABCentral(mathworks.com)......
  • Joda-Time
    https://github.com/JodaOrg/joda-time依赖引入①Maven<dependency><groupId>joda-time</groupId><artifactId>joda-time</artifactId><version>2.12.5</version></dependency>②Gradlecompile'joda-tim......
  • Math、System、Runtime //BigDecimal、Date、SimpleDaateFormat、Calendar
    1、Math =======================================================================================BigDecimal 1、构造器publicBigDecimal(Stringval)publicclassBigDecimalDemo01{publicstaticvoidmain(String[]args){//目标:掌握BigDecimal的......
  • QT常用控件之QTimer,QDialog,QLabel,QLineEdit,QProgressBar,QComboBox,QPushButton,QGridLay
    QT常用控件的组合#ifndefPROGRESSBARWIDGET_H#definePROGRESSBARWIDGET_H#include<QWidget>#include<QTimer>#include<QDialog>#include<QLabel>#include<QLineEdit>#include<QProgressBar>//显示进度条的控件#include<QComboBo......
  • Date与LocalDateTime转换
    在Java中,可以使用java.util.Date和java.time.LocalDateTime类来表示日期和时间。如果需要将Date转换为LocalDateTime,可以使用toInstant()方法将Date转换为Instant,然后再使用atZone()方法将其转换为ZoneId,最后使用toLocalDateTime()方法将其转换为LocalDateTime。示例如下:Datedat......
  • 2023-02-28-如何避免timemachine占用宝贵的mac磁盘空间
    +++title="如何避免timemachine占用宝贵的mac磁盘空间"description=""date=2023-02-28T16:47:50+08:00comment=truetoc=truereward=truecategories=[""]tags=[""]series=[]images=[]+++因为我买的MacBook只有512G的容量......