gpt4 book ai didi

Java Spring Boot 使用剩余 api 映射到模型

转载 作者:行者123 更新时间:2023-12-01 17:49:36 25 4
gpt4 key购买 nike

我正在尝试将 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]

知道为什么吗?我的类中有一个构造函数,所以我不太确定为什么会抛出错误。谢谢!

最佳答案

正如异常明确指出的那样:

(no Creators, like default construct, exist)

您的类 Person 没有默认构造函数

Any idea why?

因为您显式定义了构造函数,并且由于此行为,默认构造函数将不会自动生成。

所以你应该处理它,并且有两件事你需要关心:

  1. 提供默认构造函数,您可以显式定义它,也可以使用lombok注释@NoArgsConstructor
  2. 另一个提示可能是属性不匹配问题,如果 json 没有您的 class 定义的所有属性,您还应该通过 @JsonIgnoreProperties(ignoreUnknown = true) 显式忽略它们 到类或单独为额外字段添加 @JsonIgnore

关于Java Spring Boot 使用剩余 api 映射到模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51868938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com