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

问题:
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. 创建自定义类型转换器类,并实现 `Converter<S, T>` 接口。 2. 在Spring MVC配置类中通过编程方式注册自定义类型转换器: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addFormatters(FormatterRegistry registry) { registry.addConverter(new CustomConverter()); } } ``` 3. 确保您的配置类被正确加载,并且在Spring MVC中生效。您可以通过查看日志或调试来验证。 如果您确认配置正确,但仍然出现错误,可能是因为其他的类型转换策略或编辑器与自定义类型转换器发生冲突。在这种情况下,您可以尝试以下解决方法: 1. 检查是否存在其他的类型转换器或编辑器与您的自定义类型转换器冲突。如果有冲突,可以考虑禁用或删除冲突的类型转换器。 2. 尝试使用更具体的类型进行转换。例如,如果您的目标类型是 java.util.Date,而源类型是 java.lang.String,可以尝试使用具有更具体目标类型的自定义转换器,例如将 String 转换为 LocalDateTime,然后再将 LocalDateTime 转换为 Date。 3. 如果您在全局配置中使用了其他的转换服务(如 `FormattingConversionServiceFactoryBean`),请确保自定义类型转换器已经添加到该转换服务中。 如果您仍然遇到问题,请提供更多的代码和配置信息,以便我们可以更好地帮助您诊断和解决问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值