溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Feign日期格式轉換錯誤怎么解決

發(fā)布時間:2022-03-17 10:07:24 來源:億速云 閱讀:586 作者:iii 欄目:開發(fā)技術

本篇內(nèi)容主要講解“Feign日期格式轉換錯誤怎么解決”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Feign日期格式轉換錯誤怎么解決”吧!

出現(xiàn)的場景

  • 服務端通過springmvc寫了一個對外的接口,返回一個json字符串,其中該json帶有日期,格式為yyyy-MM-dd HH:mm:ss

  • 客戶端通過feign調用該http接口,指定返回值為一個Dto,Dto中日期的字段為Date類型

  • 客戶端調用該接口后拋異常了。

報錯異常如下

feign.codec.DecodeException: JSON parse error: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null)); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Can not deserialize value of type java.util.Date from String "2018-03-07 16:18:35": not a valid representation (error: Failed to parse Date value '2018-03-07 16:18:35': Can not parse date "2018-03-07 16:18:35Z": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS'Z'', parsing fails (leniency? null)) at [Source: java.io.PushbackInputStream@4615bc00; line: 1, column: 696] (through reference chain: com.RestfulDataBean["data"]->java.util.ArrayList[0]->com.entity.XxxDto["createTime"])    at feign.SynchronousMethodHandler.decode(SynchronousMethodHandler.java:169)    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:133)    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76)    at feign.ReflectiveFeign$FeignInvocationHandler.invoke(ReflectiveFeign.java:103)    at         com.sun.proxy.$Proxy138.queryMonitorByTime(Unknown Source)

從異常信息中我們可以看出,是在AbstractJackson2HttpMessageConverter類中調用了readJavaType方法之后拋的異常

一步一步往下深入,我們找到了最關鍵的地方,在DeserializationContext類的_parseDate方法中,執(zhí)行了df.parse(dateStr)之后拋異常了

public Date parseDate(String dateStr) throws IllegalArgumentException{      try {        DateFormat df = getDateFormat();        // 這行代碼報錯了        return df.parse(dateStr);    } catch (ParseException e) {               throw new IllegalArgumentException(String.format(                                   "Failed to parse Date value '%s': %s", dateStr, e.getMessage()));    }}

DeserializationContext是jackson的一個反序列化的一個上下文,那么它的DateFormat是從哪來的呢?我們再來看下getDateFormat的源碼

protected DateFormat getDateFormat(){       if (_dateFormat != null) {                return _dateFormat;    }    DateFormat df = _config.getDateFormat();    _dateFormat = df = (DateFormat) df.clone();        return df;}

DateFormat又是從MapperConfig而來,我們再看下config.getDateFormat()的源碼

public final DateFormat getDateFormat() {     return _base.getDateFormat(); }

我們知道,SpringMvc就是通過AbstractJackson2HttpMessageConverter類來整合jackson的,該類維護jackson的ObjectMapper,而ObjectMapper又是通過MapperConfig來進行配置的

由此可見,本異常就是因為ObjectMapper中的DateFormat無法對yyyy-MM-dd HH:mm:ss格式的字符串進行轉換所導致的

問題處理

第一種處理方式

Feign日期格式轉換錯誤怎么解決

時間屬性添加注解,進行自動轉換。

第二種方式

異常說的值服務器返回了一個帶有日期的json,日期的形式是字符串2018-03-07 16:18:35,jackson無法將該字符串轉成一個Date對象,網(wǎng)上查資料,上面說的是jackson只支持以下幾種日期格式:

  • "yyyy-MM-dd'T'HH:mm:ss.SSSZ";

  • "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";

  • "yyyy-MM-dd";

  • "EEE, dd MMM yyyy HH:mm:ss zzz";

  • long類型的時間戳

去掉服務端的以下兩個配置,讓日期返回時間戳,結果就沒報錯了

#spring.jackson.date-format=yyyy-MM-dd HH:mm:ss#spring.jackson.time-zone=Asia/Chongqing

由于服務端在其他的地方有可能和這里的配置耦合了,也就是說其他地方有可能要用到的是yyyy-MM-dd HH:mm:ss這一日期格式而不是時間戳的格式,所以這個配置肯定是不能修改的。

jackson竟然不支持yyyy-MM-dd HH:mm:ss的這種格式,肯定很不爽啦,所以下面就要開始來研究怎么讓jackson支持這種格式了。

要讓jackson支持這種格式,那么就必須修改ObjectMapper中的DateFormat,因為在ObjectMapper中,DateFormat的默認實現(xiàn)類是StdDateFormat,StdDateFormat也就只兼容了我們上述所說的幾種格式

首先我們先使用裝飾模式來創(chuàng)建一個支持yyyy-MM-dd HH:mm:ss格式的DateFormat如下

import java.text.DateFormat;import java.text.FieldPosition;import java.text.ParseException;import java.text.ParsePosition;import java.text.SimpleDateFormat;import java.util.Date; public class MyDateFormat extends DateFormat {	    private DateFormat dateFormat;	    private SimpleDateFormat format1 = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");	    public MyDateFormat(DateFormat dateFormat) {		        this.dateFormat = dateFormat;	}	    @Override	public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) {		        return dateFormat.format(date, toAppendTo, fieldPosition);	}	    @Override	public Date parse(String source, ParsePosition pos) { 		Date date = null;		        try { 			date = format1.parse(source, pos);		} catch (Exception e) { 			date = dateFormat.parse(source, pos);		}		return date;	}	// 主要還是裝飾這個方法	    @Override	public Date parse(String source) throws ParseException { 		Date date = null;		        try {						// 先按我的規(guī)則來			date = format1.parse(source);		} catch (Exception e) {			// 不行,那就按原先的規(guī)則吧			date = dateFormat.parse(source);		}		return date;	}	// 這里裝飾clone方法的原因是因為clone方法在jackson中也有用到	    @Override	public Object clone() {		Object format = dateFormat.clone();		        return new MyDateFormat((DateFormat) format);	}}

DateFormat有了,接下來的任務就是讓ObjectMapper使用我的這個DateFormat了,在config類中定義如下(本案例基于springboot)

@Configurationpublic class WebConfig {	    @Autowired	private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;		@Bean	public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() { 		ObjectMapper mapper = jackson2ObjectMapperBuilder.build();		// ObjectMapper為了保障線程安全性,里面的配置類都是一個不可變的對象		// 所以這里的setDateFormat的內(nèi)部原理其實是創(chuàng)建了一個新的配置類		DateFormat dateFormat = mapper.getDateFormat();		mapper.setDateFormat(new MyDateFormat(dateFormat)); 		MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(				mapper);		return mappingJsonpHttpMessageConverter;	}}

配置了上述代碼之后,問題成功解決。

為什么往spring容器中注入MappingJackson2HttpMessageConverter,springMvc就會用這個Converter呢?

查看springboot的源代碼如下:

@Configurationclass JacksonHttpMessageConvertersConfiguration {	@Configuration@ConditionalOnClass(ObjectMapper.class)@ConditionalOnBean(ObjectMapper.class)	@ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jackson", matchIfMissing = true)	protected static class MappingJackson2HttpMessageConverterConfiguration {		@Bean		@ConditionalOnMissingBean(value = MappingJackson2HttpMessageConverter.class, ignoredType = {				"org.springframework.hateoas.mvc.TypeConstrainedMappingJackson2HttpMessageConverter",				"org.springframework.data.rest.webmvc.alps.AlpsJsonHttpMessageConverter" })		public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter(				ObjectMapper objectMapper) {			    return new MappingJackson2HttpMessageConverter(objectMapper);		} }

默認配置為,當spring容器中沒有MappingJackson2HttpMessageConverter這個實例的時候才會被創(chuàng)建

springboot的思想是約定優(yōu)于配置,也就是說,springboot默認幫我們配好了spring mvc的Converter,如果我們沒有自定義Converter的話,那么框架就會幫我們創(chuàng)建一個,如果我們有自定義的話,那么springboot就直接使用我們所注冊的bean進行綁定

到此,相信大家對“Feign日期格式轉換錯誤怎么解決”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關內(nèi)容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI