使用JSON数据填充对象时遭遇Jackson反序列化异常求助
解决RestTemplate反序列化UsuarioDTO时的类型不匹配异常
问题根源分析
异常提示Cannot deserialize value of type java.lang.String from Object value,核心原因有两点:
- 错误的序列化注解:给
UsuarioDTO添加的@JsonFormat(shape = JsonFormat.Shape.ARRAY)会让Jackson按照JSON数组的规则解析数据,但实际接口返回的是JSON对象,导致字段映射逻辑混乱,id字段被错误识别为Object类型。 - 代码结构不合理:将
UsuarioService嵌套在UsuarioDTO中不符合Spring组件管理规范,且每次调用接口都新建RestTemplate实例会造成不必要的资源浪费。
具体修复步骤
1. 移除错误的@JsonFormat注解
修改UsuarioDTO,删除@JsonFormat(shape = JsonFormat.Shape.ARRAY),让Jackson按照JSON对象的规则解析数据:
@Getter @Setter public class UsuarioDTO implements Serializable { private static final long serialVersionUID = 1L; @JsonProperty("id") private String id; @JsonProperty("matricula") private String matricula; @JsonProperty("dv") private String dv; @JsonProperty("nome") private String nome; }
2. 重构UsuarioService,单独作为Spring组件
把Service从DTO中抽离,通过构造注入复用RestTemplate(建议提前在配置类中定义RestTemplate Bean):
@Service public class UsuarioService { private final RestTemplate restTemplate; // 构造注入RestTemplate public UsuarioService(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public UsuarioDTO consultausuario() { return restTemplate.getForEntity("http://localhost:3000/usuario/", UsuarioDTO.class).getBody(); } }
3. 确认接口返回的JSON结构
确保接口返回的JSON是与DTO字段匹配的对象结构,例如:
{ "id": "1", "matricula": "M001", "dv": "X", "nome": "João Silva" }
如果接口返回的id确实是嵌套对象(比如{"id": {"value": "1"}}),则需要修改UsuarioDTO的id字段类型为对应的实体类,示例如下:
// 定义嵌套的id实体类 public class IdDTO { @JsonProperty("value") private String value; // 生成getter和setter } // 修改UsuarioDTO的id字段 @JsonProperty("id") private IdDTO id;
额外优化建议
在Spring配置类中定义RestTemplate Bean,实现实例复用:
@Configuration public class RestTemplateConfig { @Bean public RestTemplate restTemplate() { return new RestTemplate(); } }
内容的提问来源于stack exchange,提问作者E Oliveira
相关产品推荐
相关产品推荐

