項目總結44:SpringBoot接口時間數據Json格式轉化異常MappingJackson2HttpMessageConverter


項目總結44:SpringBoot接口時間數據Json格式轉化異常MappingJackson2HttpMessageConverter

項目中,通過接口傳數據,報json解析異常,異常日志如下:

2019 09:37:27 WARN  com.hs.web.common.exception.GlobalExceptionHandler - org.springframework.http.converter.HttpMessageNotReadableException: 
JSON parse error: Can not deserialize value of type java.sql.Timestamp from String "2019-11-22 11:35:00": 
not a valid representation (error: Failed to parse Date value '2019-11-22 11:35:00': 
Can not parse date "2019-11-22 11:35:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? null)); 
nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException:
 Can not deserialize value of type java.sql.Timestamp from String "2019-11-22 11:35:00": 
 not a valid representation (error: Failed to parse Date value '2019-11-22 11:35:00': 
 Can not parse date "2019-11-22 11:35:00": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSS', parsing fails (leniency? null))
 at [Source: java.io.PushbackInputStream@27cf9ee4; line: 1, column: 44] (through reference chain: com.hs.dao.entity.xijiang.match.Match["timeStart"])

從日志中,發現時間數據"2019-11-22 11:35:00"無法匹配默認的“yyyy-MM-dd'T'HH:mm:ss.SSS”格式;導致解析失敗;

解決方案是自定義事件轉換需要匹配的格式,這里需要匹配的格式是"yyyy-MM-dd HH:mm:ss";

 

第一步,自定義DateFormat:

package com.hs.common.other;

import java.text.*;
import java.util.Date;

public class MyDateFormat extends DateFormat{

    private static final long serialVersionUID = 1L;

    private DateFormat dateFormat;
     
    private SimpleDateFormat format1 = new SimpleDateFormat("yyyy-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 {
            
            // 先按我的規則來
            date = format1.parse(source);
        } catch (Exception e) {
 
            // 不行,那就按原先的規則吧
            date = dateFormat.parse(source);
        }
 
        return date;
    }
 
    // 這里裝飾clone方法的原因是因為clone方法在jackson中也有用到
    @Override
    public Object clone() {
        Object format = dateFormat.clone();
        return new MyDateFormat((DateFormat) format);
    }
}

 

 第二步:自定義SpringBoot配置類,加載被修飾的MappingJackson2HttpMessageConverter:

package com.hs.web.boot.configuration;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hs.common.other.MyDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.text.DateFormat;


/***
 *
 * @author tyj
 *本配置目的是為了解決前端傳時間yyy-MM-dd HH:mm:ss json解析錯誤問題
 */ @Configuration public class MappingJackson2HttpMessageConverterConfig {
    @Autowired
    private Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder;

    @Bean
    public MappingJackson2HttpMessageConverter MappingJsonpHttpMessageConverter() {

        ObjectMapper mapper = jackson2ObjectMapperBuilder.build();

        // ObjectMapper為了保障線程安全性,里面的配置類都是一個不可變的對象
        // 所以這里的setDateFormat的內部原理其實是創建了一個新的配置類
 DateFormat dateFormat = mapper.getDateFormat(); mapper.setDateFormat(new MyDateFormat(dateFormat));

        MappingJackson2HttpMessageConverter mappingJsonpHttpMessageConverter = new MappingJackson2HttpMessageConverter(
                mapper);
        return mappingJsonpHttpMessageConverter;
    }
}

 當項目啟動后MappingJackson2HttpMessageConverter被加載,"yyyy-MM-dd HH:mm:ss"格式的事件可以被正確解析;

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM