日期格式转换异常:Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module \"com.fasterxml.jackson.datatype:jackson-datatype-jsr310

异常信息:

"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;
    }
}

 

posted @ 2023-10-11 14:23  BlogMemory  阅读(2623)  评论(0编辑  收藏  举报