我正在尝试将 API 的响应映射到我的对象:
class Person {
private Long id;
private String firstname;
private String lastname;
public Person(Long id, String firstname, String lastname)
...
我的 api 调用如下所示:
RestTemplate restTemplate = new RestTemplate();
Person person = restTemplate.getForObject("http://xxx/getPerson", Person.class);
它返回一个如下所示的 json:
{
"id": 1,
"firstname": "first",
"lastname": "last"
}
不幸的是,我收到以下错误:
Type definition error: [simple type, class xxx.Person]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `xxx.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)\n at [Source: (PushbackInputStream); line: 4, column: 5]
知道为什么吗?我的班级中有一个构造函数,所以我不太确定为什么会抛出错误。谢谢!
正如例外明确指出的那样:
(没有创建者,如默认构造,存在)
您的类没有默认构造函数Person
。
知道为什么吗?
因为您显式定义了一个构造函数并且正是由于这种行为,所以不会自动生成默认构造函数。
所以你应该处理它,你需要关心两件事:
default constructor
您明确定义它或使用lombok注释@NoArgsConstructor
;class
定义的所有属性,您还应该通过@JsonIgnoreProperties(ignoreUnknown = true)
类显式忽略它们或@JsonIgnore
单独添加额外字段。本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句