使用WebClient调用接口输出序列化请求时,LocalDateTime序列化后是数组格式

这里引用我之前遇到的情况,其实差不多
链接

环境

springboot3.02

问题

在使用WebClient调用接口的时候,接口序列化LocalDateTime类型的属性的时候,发现输出的又是数组:[年, 月, 日, 小时, 分钟, 秒, 毫秒]的格式,和我上面的链接一样。

原因

还是Jackson的问题。WebClient还是使用的Jackson进行的序列化,但是我不知道是不是Jackson的版本导致的,知道的评论踢我一下。

处理方式

参照我之前链接的方式进行优化,主要利用的WebClient的 .exchangeStrategies(ExchangeStrategies类型)来自定义序列化方式。

//以一个Test方法作为示例
public void test() throws JsonProcessingException {
  		ObjectMapper mapper = new ObjectMapper();
  		// 禁止将日期时间作为时间戳写出
  		mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        JavaTimeModule javaTimeModule = new JavaTimeModule();

		 // 添加序列化器
        javaTimeModule
        	.addSerializer(LocalDateTime.class, 
        	new LocalDateTimeSerializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME));

		// 添加反序列化器
        javaTimeModule
        	.addDeserializer(LocalDateTime.class,
        	new LocalDateTimeDeserializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 

		// 注册模块
        mapper.registerModule(javaTimeModule); 
        ExchangeStrategies.builder()
                .codecs(configurer -> {
                    configurer
                    	.defaultCodecs()
                    	.jackson2JsonEncoder(
                    	new Jackson2JsonEncoder(objectMapper)); 
                    configurer
                    	.defaultCodecs()
                    	.jackson2JsonDecoder(
                    	new Jackson2JsonDecoder(objectMapper)); 
                })
                .build();

        Map<String, Object> map = new HashMap<>();
      	LocalDateTime time = LocalDateTime.now();
        map.put("time", time);
        
		//定义客户端
		WebClient webClient = WebClient.builder()
				//重点在下面这里,使用上面定义的strategies,修改默认的序列化/反序列化行为。
				.exchangeStrategies(strategies)

				//其他的配置
                .baseUrl("http://api.test.com")
                .defaultHeader("Content-Type", "application/json")
                .build();
        //发送请求        
        webClient.post()
                .uri("/test")
                .body(Mono.just(map), Map.class)
                .retrieve().
                bodyToMono(Map.class).
                subscribe(System.out::println);
    }

最后得到的JSON格式为:

{“time” : “2024-07-03T21:41:41.2659011”}

可以去调整mapper的内容,尝试序列化输出其他格式。

  • 9
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值