0

I need to consume a REST endpoint using spring RestTemplate. Below is the sample response from the endpoint and I need to fetch nested employee json and map it to model object. I found various complex solutions like

  • Deserializing response to a wrapper object and then fetching Employee object from it
  • Getting the response as a string and then converting it to json and deserializing

None of these solutions are simple and clean. Not sure if there is a clean and automatic way of doing it like this

ResponseEntity<Employee> response = restTemplate.exchange(URL,..?..);

Response -

{
    "employee": {
        "id": "123",
        "first_name": "foo",
        "last_name": "bar"

    },
    "session": {
        "id": "1212121",
        "createdDate": "2022-08-18T19:35:30Z"
    }
}

Model object -

public class Employee {
    
    private long emplId;
    private String fName;
    private String lName;
}

1 Answers1

0

RestTemplate can do all of this for you, but first, your object doesn't match your response.

Ideally, you would have a Class that has an Employee and Session, like this

public class HaveSomeClassMan {
  private Employee employee;
  private Session session;
}

Then you can do

HaveSomeClassMan haveSomeClassMan = restTemplate.postForObject("URL", "requestObject", HaveSomeClassMan.class);

But, since you already have a JSON string, here's how you can convert it to a JSONObject, get the Employee out of it, and use the ObjectMapper to convert it to an Employee object.

JSONObject jsonObject = new JSONObject(s); // where s is your json string
String theEmployee = jsonObject.get("employee").toString(); // get the "employee" json from the JSONObject

Employee employee = new ObjectMapper().readValue(theEmployee, Employee.class);  // Use the object mapper to convert it to an Employee

You do need to pay attention, though, as your model doesn't line up with your json. Your model calls the first name field, fname, yet your json has this as first_name. These properties all need to line up. If you want to keep your model as you've defined it, you need to annotate your fields with what their corresponding json field is, like this:

@JsonProperty("first_name")
private String fName;

This tells the mapper to map the JSON field first_name to the property fName. Regardless of whether you let RestTemplate do the mapping for you or you do it manually via the JSONObject approach, your model needs to match your JSON string. You can do this implicitly just by naming the fields in your model the same as they are in your JSON, or explicitly by adding the @JsonProperty to each field that doesn't implicitly map.

lane.maxwell
  • 5,002
  • 1
  • 20
  • 30