Search code examples
javajsonspringresttemplatejackson2

Should RestTemplate (w/ Jackson) Call Fail If JSON Has an Invalid Property Name


I have the following REST call with Spring's (5.0.1) RestTemplate and Jackson 2 (fasterxml) converter:

final List<HttpMessageConverter<?>> messageConverters =   restTemplate.getMessageConverters();

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();

final ObjectMapper objectMapper = converter.getObjectMapper();
objectMapper.enable(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL);

restTemplate.getMessageConverters().add(converter);

What I don't understand is when the response from the server has an unknown JSON property, it simply sets it to null vs. what I had assumed RestTemplate#getForEntity() throwing an exception during data extraction:

ResponseEntity<MyResponse> responseEntity = restTemplate.getForEntity("http//some-url/api", MyResponse.class); 

Mapping object is simply a Serializable and does not have any Jackson annotation:

public class MyResponse implements Serializable {
  private String propertyOne;
  private String propetyTwo;
}

A response JSON looks like:

{ 
   "propertyOne":"one",
   "badName":"two"    
} 

The mapped object contains a value for propertyOne but null for badName in this case.

Is RestTemplate/Jackson not throwing any exception/error normal in these cases?

What if I want to force the call to throw an exception?


Solution

  • Use FAIL_ON_UNKNOWN_PROPERTIES

    Feature that determines whether encountering of unknown properties (ones that do not map to a property, and there is no "any setter" or handler that can handle it) should result in a failure (by throwing a JsonMappingException) or not. This setting only takes effect after all other handling methods for unknown properties have been tried, and property remains unhandled.

    Feature is enabled by default (meaning that a JsonMappingException will be thrown if an unknown property is encountered).

    Example :

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);