【问题标题】:How can i get content of Page as List<AnyDTO> and not as List<java.util.LinkedHashMap> with RestTemplate in Kotlin如何在 Kotlin 中使用 RestTemplate 将 Page 的内容作为 List<AnyDTO> 而不是 List<java.util.LinkedHashMap>
【发布时间】:2026-02-07 17:45:01
【问题描述】:

控制器接口

interface BrandController {
    fun findDTOs(pageable: Pageable): ResponseEntity<Page<SomeDTO>>
}

简化了我的测试

var response: ResponseEntity<*>

@Test
fun `test`() {
    `given TestRestTemplate`() 
    `when findDTOs`()
    `then check body`()
}

protected fun `given not authorization`() {
    restTemplate = TestRestTemplate()
}

private fun `when findDTOs`() {
    // RestResponsePage<T> extends PageImpl<T>
    response = restTemplate.getForEntity<RestResponsePage<SomeDTO>>(createUrlWithParams(url, requestPage))
}

private fun `then check body`() {
    val body: Page<SomeDTO> = response.body as Page<SomeDTO> // body: "Page 2 of 2 containing java.util.LinkedHashMap instances"

    assertEquals(requestPage.size, body.size) // success

    val content: List<SomeDTO> = body.content as List<SomeDTO> // content: size = 10 body: "Page 2 of 2 containing java.util.LinkedHashMap instances"

    content.forEachIndexed { index, someDTO: SomeDTO-> //Error
        assertEquals(expectedList[index].name, someDTO.name)
        assertEquals(expectedList[index].id, someDTO.id)
    }
}

错误是:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com....SomeDTO

如何以List&lt;AnyDTO&gt; 而不是List&lt;java.util.LinkedHashMap&gt; 获得页面内容

我这样做是为了通过TestRestTemplate返回JSON String来验证内容的正确性,但是我想这样做

【问题讨论】:

    标签: spring-boot kotlin resttemplate


    【解决方案1】:

    我不能说这里的具体问题是什么,但我通常不会使用PageImpl 来表示我的分页资源。你应该看看Spring HATEOAS

    您需要做的是扩展ResourceSupport

    class PaginatedRestResponse(val dtos: List<AnyDTO>) : ResourceSupport()
    

    这将为您的班级提供hateoas 链接。然后你可以调用 restTemplate 接受这个类型:

    response = restTemplate.getForEntity<PaginatedRestResponse>(createUrlWithParams(url, requestPage))
    

    您可以这样检索链接:

    response.getLink(Link.REL_NEXT)
    response.getLink(Link.REL_PREVIOUS)
    

    【讨论】:

      【解决方案2】:

      您可以使用“ParameterizedTypeReference”。像这样的:

      val response = restTemplate.exchange("/messages/$username", HttpMethod.GET, null,
              object : ParameterizedTypeReference<List<Message>>() {})
      

      【讨论】: