java - 如果 JSON 具有无效的属性名称,RestTemplate(w/Jackson)调用应该失败

标签 java json spring resttemplate jackson2

我使用 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 值,但 badNamenull

在这些情况下,RestTemplate/Jackson 不会引发任何异常/错误吗?

如果我想强制调用抛出异常怎么办?

最佳答案

使用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).

示例:

objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,true);

关于java - 如果 JSON 具有无效的属性名称,RestTemplate(w/Jackson)调用应该失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56720744/

相关文章:

java - 如何更改二维数组中的所有值?

javascript - 具有可变值的 Json 响应

java - 在jsf中使用spring时的bean实例化异常

java - 领域对象中的业务逻辑

java.lang.OutOfMemory错误: GC overhead limit exceeded : Application deployed in weblogic

java - 使用 Mockito 测试抽象类

java - android http URL 连接适用于 https,不适用于 http

java - Jackson: map 反序列化

java - 无法使用 Jackson 解析 JSON(映射不起作用)

java - 如何在自定义查询中加载@ElementCollection?