Search code examples
javaspring-bootresttemplate

Convert a response object to entity in spring boot resttemplate


I am calling an endpoint that returns back a JSON response. Here is sample of the JSON response:

{
    "main": {
        "test":{
            "Date": "2022-06-06",
            "Id": 1234
        },
        "response" :[
            {
            "responseTime": 100,
            "redirects": 0
            }
        ]
    }
}

Here is my code to get the JSON response:

HttpEntity<String> request = new HttpEntity<>(setHeaders());
            ResponseEntity<Main> response = restTemplate.exchange(endpoint, HttpMethod.GET, request, Main.class);

I want to convert the response to an entity object, with the response section being a HashMap. I tried the following but I get an error that the conversion failed

public class Main {
    private Test test;
    private Response response;
}

public class Test{
  private Date Date;
  private int Id;
}

public class Response{
private Map<String, String> responseMap;
}

Can someone help me understand what I am doing wrong?


Solution

  • what you are getting back is an Object containing a main object

    {
        "main": {
            "test":{
                "Date": "2022-06-06",
                "Id": 1234
            },
            "response" :[
                {
                "responseTime": 100,
                "redirects": 0
                }
            ]
        }
    }
    

    which means

    // Can be named whatever
    public class Response {
        private Main main;
    
        //constructor, getter setters
    }
    
    public class Main {
        private Test test;
        private ArrayList<Data> response;
    
        //constructor, getter setters
    }
    
    public class Test {
        private LocalDate date;
        private int id;
    
        //constructor, getter setters
    }
    
    public class Data {
        private int responseTime;
        private int redirects;
    
        //constructor, getter setters
    }
    

    And then you call and plase the response data in the top level object

    ResponseEntity<Main> response = restTemplate.exchange(endpoint, HttpMethod.GET, request, Response.class);