如何使用 spring test resttemplate in java 将结果转换为特定模型类型以访问该模型中的字段?

How to cast results to specific model type to access the field in that Model using spring test resttemplate in java?

参考下面的代码,我试图将结果转换为 Profile 类型模型并迭代它以获取字段。但我收到 class 转换异常。请参阅下面附带的示例响应,需要从结果中获取 pid。

//code

    // search profile by profileId
    SearchCriteria sc = new SearchCriteria(Profile.PROFILE_ID, EQUALS, profileId);
    SearchInput searchInput = SearchInput.builder().criteria(sc).build();


  HttpEntity<SearchInput> searchRequest = new HttpEntity<>(searchInput);
            PageableResponse response = restTemplate.postForObject(searchUrl, searchRequest, PageableResponse.class);
            Object results =  response.getResults();
            ArrayList<Profile>  profiles =  (ArrayList<Profile>) results;
            System.out.println(profiles.get(0));
            for(Profile p: profiles) {
            log.trace(p.getId());   
            }   
        }

错误日志:

java.lang.ClassCastException: class java.util.LinkedHashMap cannot be cast to class com.model.profile.Profile (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; com.palmtree.matrimony.model.profile.Profile is in unnamed module of loader 'app')
        at com..integration.ProfileSearchIntegrationTest.searchProfileByProfileId(ProfileSearchIntegrationTest.java:97)
    

// 示例响应

{
    "total": 1095,
    "page": 0,
    "size": 50,
    "results": [
        {
            "id": "_AGi3ncBn8p1nefEm0Oe",
            "cdt": "2021-02-26T13:58:54.563Z",
            "mdt": "2021-02-26T13:58:54.563Z",
            "pid": 12038422,
            "ps": "Draft"...}]

我将此作为答案重新发布,因为它可能有助于 OP 解决问题。

您可以尝试使用 restTemplate.exchange() 方法并将 PageableResponse<Profile> 作为类型传递给 ParameterizedTypeReference。我认为您不应该将 PageableResponse 用于 return 类型,因为您没有在此测试中测试分页。