简体   繁体   中英

how to call restTemplate.postForEntity when entity is having different field name than expected

I am having a rest API which accept entity with field names as id,title. But when calling I am having different fields with same value as id,description.

How to modify the call so that I can make the request.

In the below code, Employee class is having two fields id, desc which are different from id,title.

public ResponseEntity<Employee> postForEntity(Employee newEmployee) {
  MultiValueMap<String, String> headers = new HttpHeaders();
  headers.add("User-Agent", "EmployeeRestClient demo class");
  headers.add("Accept-Language", "en-US");
  HttpEntity<Employee> entity = new HttpEntity<>(newEmployee, headers);
  return restTemplate.postForEntity(REQUEST_URI, entity, Employee.class);
}

First make sure that if the class Employee is correct on this place. If correct, then map Java properties to JSON as follows:

public class Employee {
    ... id; // name remains unchanged

    @JsonProperty("title")
    ... desc;

}

If you cannot modify Employee class, create another one with needed property names and copy instance of Employee to your instance of your class, and then user this instance in the restTemplate .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM