执行RestTemplate请求时遇HttpMessageNotReadableException日期解析错误
Hey, let's work through this date parsing error you're hitting with HttpMessageNotReadableException—Jackson is trying to parse the value 'I' as a valid date, which obviously doesn't work. Here's how to diagnose and fix it:
1. First, check the raw API response
Start by calling your target URL directly (use tools like curl, Postman, or even a browser if it's a GET request) to look at the raw JSON output. You’ll almost certainly find that one of the date fields mapped to your ShiftPlannerModel class is returning 'I' instead of a proper date string. This is usually a backend issue—maybe the database has invalid data in a date column, or the API is mishandling serialization for that field.
2. Verify date field annotations in ShiftPlannerModel
Double-check the date-type fields (like java.util.Date or java.time.LocalDateTime) in your ShiftPlannerModel class. If your API returns dates in a custom format, you need to explicitly tell Jackson how to parse them with annotations:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date shiftStartTime;
Without this annotation, Jackson uses its default date format, and any mismatch will trigger a parsing failure.
3. Configure your RestTemplate's ObjectMapper properly
While you added MappingJackson2HttpMessageConverter, you might not have set up a date formatter that matches your API's output. Try configuring the ObjectMapper explicitly to handle dates correctly:
RestTemplate restTemplate = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // For java.util.Date types objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); // For Java 8 date/time types (LocalDateTime, LocalDate, etc.) objectMapper.registerModule(new JavaTimeModule()); converter.setObjectMapper(objectMapper); restTemplate.getMessageConverters().add(converter);
This gives Jackson a clear rule set for parsing dates, eliminating unexpected format mismatches.
Quick debugging trick to pinpoint the issue
If you’re still stuck, print the raw JSON response before deserializing to identify exactly which field has the invalid 'I' value:
// Fetch the raw JSON string first String rawApiResponse = restTemplate.getForObject(URL, String.class); System.out.println("Raw API Response: " + rawApiResponse); // Attempt manual deserialization to see where it breaks ObjectMapper mapper = new ObjectMapper(); // Add the same date configuration as above if needed ShiftPlannerModel[] models = mapper.readValue(rawApiResponse, ShiftPlannerModel[].class);
This will show you the exact field causing the failure, making it easier to fix the root problem.
内容的提问来源于stack exchange,提问作者Elias

