Jackson MismatchedInputException异常:用户组POST请求问题排查
Looks like you're hitting a common snag when working with Spring Data REST's HAL (Hypertext Application Language) format alongside a custom OAuthRestTemplate setup. Let's break down the fixes step by step:
1. Complete Your ObjectMapper HAL Configuration
Just registering Jackson2HalModule isn't enough—you need to add the HalHandlerInstantiator to properly parse HAL-specific fields like _links and _embedded. Here's the full, working configuration:
ObjectMapper objectMapper = new ObjectMapper(); Jackson2HalModule halModule = new Jackson2HalModule(); objectMapper.registerModule(halModule); // Critical: This handles HAL's special properties during serialization/deserialization objectMapper.setHandlerInstantiator(new Jackson2HalModule.HalHandlerInstantiator( new DefaultRelProvider(), null, null )); // Disable failing on unknown properties (HAL adds fields like _links that aren't in your UserGroup class) objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
2. Bind Your Custom ObjectMapper to OAuthRestTemplate
A frequent mistake is that OAuthRestTemplate uses its default ObjectMapper instead of your HAL-configured one. Replace its default message converter with your HAL-aware version:
// Create a message converter that uses your custom ObjectMapper MappingJackson2HttpMessageConverter halConverter = new MappingJackson2HttpMessageConverter(); halConverter.setObjectMapper(objectMapper); // Explicitly support the HAL JSON media type halConverter.setSupportedMediaTypes(Collections.singletonList(MediaTypes.HAL_JSON)); // Swap out the default converter in your OAuthRestTemplate List<HttpMessageConverter<?>> converters = oauthRestTemplate.getMessageConverters(); converters.removeIf(c -> c instanceof MappingJackson2HttpMessageConverter); converters.add(halConverter);
3. Ensure Your POST Request Uses HAL Media Type
When sending the request, set the Content-Type to application/hal+json so the server understands the format, and your client can correctly parse the HAL response:
public UserGroup createUserGroup(UserGroup userGroup) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaTypes.HAL_JSON); HttpEntity<UserGroup> requestEntity = new HttpEntity<>(userGroup, headers); ResponseEntity<UserGroup> userGroupResponseEntity = oauthRestTemplate .postForEntity(GROUPS_ENDPOINT, requestEntity, UserGroup.class); return userGroupResponseEntity.getBody(); }
4. Adjust Your UserGroup Class for HAL Compatibility
Add @JsonIgnoreProperties to your UserGroup class to ignore any HAL-specific fields that don't map to your entity's properties:
@JsonIgnoreProperties(ignoreUnknown = true) public class UserGroup { // Your existing fields, constructors, and methods }
These changes ensure both your request and response are properly serialized/deserialized using HAL format, which should resolve the MismatchedInputException you're seeing.
内容的提问来源于stack exchange,提问作者Stefan Falk

