问题:
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;
}
}