当前位置:   article > 正文

SpringMVC日期解析问题(SON parse error: Cannot deserialize value of type `java.util.Date` from String.....)

son parse error: cannot deserialize value of type `java.util.date` from stri
问题:
JSON parse error: Cannot deserialize value of type java.util.Date from String “2016-10-05”: not a valid representation (error: Failed to parse Date value ‘2016-10-05’: Unparseable date: “2016-10-05”); nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type java.util.Date from String “2016-10-05”: not a valid representation (error: Failed to parse Date value ‘2016-10-05’: Unparseable date: “2016-10-05”) at [Source: (PushbackInputStream); line: 1, column: 83] (through reference chain: com.ztax.ifrs9.param.entity.ProspecRf[“availabilityDate”])]
原因:

接收前端的日期格式为java.lang.String,然而对象中是java.util.Date,所以无法将字符串格式的日期值解析为日期格式

解决:

添加配置类如下

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import com.fasterxml.jackson.databind.ObjectMapper;
 
@Configuration
public class WebConfig {
	@Bean
    public MappingJackson2HttpMessageConverter getMappingJackson2HttpMessageConverter() {
    	MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
    	//日期格式
    	ObjectMapper objectMapper = new ObjectMapper();
    	SimpleDateFormat smt = new SimpleDateFormat("yyyy-MM-dd");
    	objectMapper.setDateFormat(smt);
    	mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
    	//编码格式
    	List<MediaType> list = new ArrayList<MediaType>();
    	list.add(MediaType.APPLICATION_JSON_UTF8);
    	mappingJackson2HttpMessageConverter.setSupportedMediaTypes(list);
    	return mappingJackson2HttpMessageConverter;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/692576
推荐阅读
相关标签
  

闽ICP备14008679号