Spring RestTemplate无法反序列化嵌套JSON数组问题
解决RestTemplate反序列化嵌套JSON数组为null的问题
针对你遇到的RestTemplate接收响应后,systemCall列表始终为null的问题,可尝试以下几种解决方案:
1. 显式指定字段映射(@JsonProperty)
在实体类的systemCall字段上添加@JsonProperty注解,明确绑定JSON中的字段名,避免命名策略匹配问题:
public class Resolution { // 其他字段... @JsonProperty("systemCall") private List<SystemCallVo> systemCall; // Getters and Setters }
同时给SystemCallVo的字段也添加该注解,确保每个字段都能正确映射:
public class SystemCallVo { @JsonProperty("creationTime") private String creationTime; @JsonProperty("status") private String status; @JsonProperty("id") private String id; @JsonProperty("modificationTime") private String modificationTime; @JsonProperty("creatorId") private String creatorId; // Getters and Setters }
2. 添加忽略未知属性注解
如果响应JSON中存在实体类未定义的字段,可能干扰反序列化过程,给实体类添加@JsonIgnoreProperties(ignoreUnknown = true):
@JsonIgnoreProperties(ignoreUnknown = true) public class Resolution { // 字段和方法... } @JsonIgnoreProperties(ignoreUnknown = true) public class SystemCallVo { // 字段和方法... }
3. 检查RestTemplate的消息转换器配置
确保RestTemplate使用的Jackson ObjectMapper配置正确,没有禁用字段自动检测。可自定义RestTemplate的消息转换器:
@Bean public RestTemplate restTemplate() { RestTemplate restTemplate = new RestTemplate(); MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(); ObjectMapper objectMapper = new ObjectMapper(); // 启用字段自动检测,确保私有字段能被访问 objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY); converter.setObjectMapper(objectMapper); restTemplate.getMessageConverters().add(0, converter); return restTemplate; }
4. 验证响应Content-Type
确认接口返回的HTTP响应头中Content-Type为application/json,如果是其他类型(比如text/plain),RestTemplate可能不会使用Jackson进行反序列化,导致嵌套数组无法解析。
5. 尝试直接使用父类接收响应
暂时替换ResolutionVo为Resolution接收响应,排查是否是继承导致的反序列化问题:
ResponseEntity<List<Resolution>> response = this.restTemplateConfig.restTemplate().exchange( builder.toUriString(), HttpMethod.POST, httpEntity, new ParameterizedTypeReference<List<Resolution>>() {} );
如果此方式能正确解析systemCall,再排查ResolutionVo是否存在未正确继承的问题。
内容的提问来源于stack exchange,提问作者Pawan Patil
相关产品推荐
相关产品推荐

