我有以下简单的测试
import org.springframework.web.client.RestTemplate;
import pages.TimezonePage;
class GETSimple
{
private RestTemplate restTemplate;
private String URL = "http://worldtimeapi.org/api/timezone/America/Los_Angeles";
@BeforeEach
void setUp()
{
restTemplate = new RestTemplate();
}
@Test
void GETasPOJO()
{
TimezonePage response = restTemplate.getForObject(URL, TimezonePage.class);
assertEquals("PDT", response.getAbbreviation());
assertTrue(response.getDst());
}
}
这适用于具有 getter 和 setter 的 TimezonePage 类。
pom.xml 的相关部分如下
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.10.3</version>
</dependency>
我创建了一个 Java 14 记录 TimezoneRecord,其变量与 TimezonePage 相同,但没有 getter 和 setter。然后我用
TimezoneRecord response = restTemplate.getForObject(URL, TimezoneRecord.class);
没有语法错误。运行测试时,我收到以下异常
org.springframework.http.converter.HttpMessageConversionException: Type definition error: [simple type, class pages.TimezoneRecord]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `pages.TimezoneRecord` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
有什么办法可以解决吗?或者我不能将杰克逊与记录一起用作 POJO?谢谢,弗拉基米尔