码迷,mamicode.com
首页 > 移动开发 > 详细

项目总结44:SpringBoot接口时间数据Json格式转化异常MappingJackson2HttpMessageConverter

时间:2019-11-16 10:42:02      阅读:308      评论:0      收藏:0      [点我收藏+]

标签:except   text   back   总结   解析异常   fail   pac   center   appendto   

项目总结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;
    }
}

 

项目总结44:SpringBoot接口时间数据Json格式转化异常MappingJackson2HttpMessageConverter

标签:except   text   back   总结   解析异常   fail   pac   center   appendto   

原文地址:https://www.cnblogs.com/wobuchifanqie/p/11870750.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!