首页 > 其他分享 >使用Spring HttpExchange时数据对象遇LocalDateTime字段类型json反序列化失败的解决方法

使用Spring HttpExchange时数据对象遇LocalDateTime字段类型json反序列化失败的解决方法

时间:2024-05-17 17:08:08浏览次数:19  
标签:HttpExchange converter Spring dd yyyy javaTimeModule new 序列化 objectMapper

方法:重写MessageConverter, 使得yyyy-MM-dd HH:mm:ss的字符串能反序列化到LocalDateTime类型上。

@Configuration
public class HttpClientConfig {

    @Value("${service.host}")
    private String host;

    @Bean
    RestClient.Builder restClientBuilder() {
        return RestClient.builder();
    }

    @Bean
    public HttpServiceProxyFactory httpServiceProxyFactory(RestClient.Builder restClientBuilder) {
        HttpExchangeAdapter httpExchangeAdapter = RestClientAdapter.create(
                restClientBuilder.baseUrl(host)
                        .messageConverters(httpMessageConverters -> {
                            httpMessageConverters.stream()
                                    .filter(converter -> converter instanceof MappingJackson2HttpMessageConverter)
                                    .map(converter -> (MappingJackson2HttpMessageConverter) converter).forEach(converter -> {
                                        converter.setObjectMapper(customObjectMapper());
                                        converter.setPrettyPrint(true);
                                        List<MediaType> mediaTypes = new ArrayList<>(converter.getSupportedMediaTypes());
                                        mediaTypes.add(MediaType.APPLICATION_JSON);
                                        converter.setSupportedMediaTypes(mediaTypes);
                                    });
                        })
                        .build()
        );
        return HttpServiceProxyFactory
                .builder()
                .exchangeAdapter(httpExchangeAdapter)
                .build();
    }


    public ObjectMapper customObjectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        // 其他配置...
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        // 匹配不上的字段忽略,宽松模式
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 允许出现特殊字符和转义符
        objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
        // 允许出现单引号
        objectMapper.configure(com.fasterxml.jackson.core.JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addSerializer(Date.class, new DateSerializer(false, new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")));

        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        javaTimeModule.addDeserializer(Date.class, new com.fasterxml.jackson.databind.JsonDeserializer<Date>() {
            @Override
            public Date deserialize(com.fasterxml.jackson.core.JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
                try {
                    return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(p.getText());
                } catch (ParseException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        objectMapper.registerModule(javaTimeModule);
        return objectMapper;
    }

}

标签:HttpExchange,converter,Spring,dd,yyyy,javaTimeModule,new,序列化,objectMapper
From: https://www.cnblogs.com/jiayuan2006/p/18198117

相关文章

  • SpringCloud解决feign调用token丢失问题
    背景讨论feign请求在微服务环境中,完成一个http请求,经常需要调用其他好几个服务才可以完成其功能,这种情况非常普遍,无法避免。那么就需要服务之间的通过feignClient发起请求,获取需要的资源。认证和鉴权一般而言,微服务项目部署环境中,各个微服务都是运行在内网环境,网关服务负责请......
  • SpringMVC中的异常处理机制
    1.概述SpringMVC提供了基于xml和基于注解的异常处理机制,一般情况下两者都要进行配置,xml异常处理机制主要用于处理xml方式产生的异常,注解异常处理机制主要用于处理基于注解方式产生的异常。2.基于xml方式的异常处理机制<!--配置基于xml的异常映射--><beanid="simpleMapp......
  • spring security 使用过滤器认证登录时,抛出自定义异常
    前情提要最近在做项目的改造,涉及到新增用户的离职冻结状态,当被离职/冻结后,尝试登录系统,则抛出不同的异常代码给前端,前端依据不同的异常代码提示不同的文本。所以需要对项目的认证逻辑简单调整,增加按照不同的登录用户的状态(离职/冻结)判断,如果满足指定状态,则抛出对应的异常代码。......
  • Spring Boot的常用注解
    在SpringBoot中,注解(Annotation)是核心特性之一,广泛用于配置和简化开发。以下是SpringBoot中一些常用的注解及其示例:1.@SpringBootApplication@SpringBootApplication是一个组合注解,包括了@Configuration、@EnableAutoConfiguration和@ComponentScan。它通常用在主类上,标识一个......
  • SpringBoot给所有的 Model添加属性
    添加全局数据@ControllerAdvice是一个全局数据处理组件,因此也可以在@ControllerAdvice中配置全局数据,使用@ModelAttribute注解进行配置,代码如下: 运行测试结果:  ......
  • Springcloud学习笔记67--springboot 整合 任务调度框架Quartz
    1.背景定时任务Job的作业类中无法注入Service等由Spring容器所管理的Bean。例如下面这种情况,TaskCronJobService就无法成功注入。importjava.util.Iterator;importjavax.annotation.Resource;importorg.quartz.Job;importorg.quartz.JobExecutionContext;importor......
  • springboot集成@DS注解实现数据源切换(转载)
    springboot集成@DS注解实现数据源切换启用@DS实现数据源切换POM内添加核心jar包yml配置"核心"-使用@DS注解最后启用@DS实现数据源切换POM内添加核心jar包 <dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-start......
  • springboot怎么将List集合数据转成JSON数组
    SpringBoot默认使用Jackson框架将Java对象转换成JSON格式。要转换List集合数据为JSON数组,可以采用以下两种方法:1.使用@ResponseBody注解在SpringBoot中,可以使用@ResponseBody注解标注要返回的List集合数据,让Spring自动将其转换成JSON数组。例如:@GetMapping("/list")@Respo......
  • 关于SpringBoot项目使用Hutool工具进行json序列化时出现Null值过滤或者丢失的问题(转
    ##问题描述:SpringBoot项目中,一直使用的时Hutool的json转换工具,被强制要求不能使用fastJson工具;之前都没什么问题,突然有一次使用parseObj()进行json字符串转换json对象时,突然报错:Noserializerfoundforclasscn.hutool.json.JSONNullandnopropertiesdiscoveredtocreate......
  • Springcloud学习笔记66---@Autowired注入为null的几种情况
    1.在应用的Filter或Listener中使用了@Autowired原因:因为Filter和Listener加载顺序优先于spring容器初始化实例,所以使用@Autowired肯定为null了~~解决:用ApplicationContext根据bean名称(注意名称为实现类而不是接口)去获取bean,随便写个工具类即可2.你写的代码有问题,没加@Service、......