我使用 Spring (5.0.1) RestTemplate
和 Jackson 2 (fasterxml) 转换器进行以下 REST 调用:
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);
我不明白的是,当服务器的响应具有未知的 JSON 属性时,它只是将其设置为 null
与我假设的 RestTemplate#getForEntity()
数据提取期间抛出异常:
ResponseEntity<MyResponse> responseEntity = restTemplate.getForEntity("http//some-url/api", MyResponse.class);
映射对象只是一个Serialized
并且没有任何Jackson注释:
public class MyResponse implements Serializable {
private String propertyOne;
private String propetyTwo;
}
响应 JSON 如下所示:
{
"propertyOne":"one",
"badName":"two"
}
在本例中,映射对象包含 propertyOne
值,但 badName
为 null
。
在这些情况下,RestTemplate
/Jackson
不会引发任何异常/错误吗?
如果我想强制调用抛出异常怎么办?
最佳答案
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).
示例:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);
关于java - 如果 JSON 具有无效的属性名称,RestTemplate(w/Jackson)调用应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720744/