0

Refer the below code, I am trying to cast the results to the Profile type model and iterating it to get the field. But I am getting class cast exception. Refer to the sample response attached below, Need to fetch pid from results.

//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());   
            }   
        }

Error log:

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)
    

// sample response

{
    "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"...}]
selvi
  • 1,271
  • 2
  • 21
  • 41
  • please provide code of the class `SearchInput`, specify what is `searchInput` variable and what is response is expected for your POST request – Andrey Mar 01 '21 at 11:59
  • @Andrey Refer to the updated question – selvi Mar 01 '21 at 12:23
  • 1
    You can try to use `restTemplate.exchange()` method and pass `PageableResponse` as a type in `ParameterizedTypeReference`. I think you shouldn't use PageableResponse for return type as you are not testing pagination in this test. – Andrey Mar 02 '21 at 07:09
  • Thanks, modified model and adopted your solution@Andrey – selvi Mar 03 '21 at 04:37

1 Answers1

1

I repost this as the answer as it might helped to the OP solve the problem.

You can try to use restTemplate.exchange() method and pass PageableResponse<Profile> as a type in ParameterizedTypeReference. I think you shouldn't use PageableResponse for return type as you are not testing pagination in this test.

Andrey
  • 433
  • 1
  • 5
  • 19