0

Currently, I'm creating REST Service with Spring.

My request handler in @RestController:

@RequestMapping(value = "employees/", method = RequestMethod.POST)
public Response setEmployees(@RequestBody Employee employee) {
    Response response = employeeManager.setEmployee(employee);
    return response;
}

Employee has fields like: login,tabNumber,firstName etc.

The real problem is that my REST service customers want to send request with another field names, that does not corresponds to Java naming conventions. Like TABNUMBER, UNITS_NAME etc. Jackson API converts JSON data to Java object corresponding to it field names... How to solve it? How can I bind custom JSON field names to my Java object field names?


catscoolzhyk
  • 675
  • 10
  • 29
  • You can create one request Entity as per the JSON Request and one Business Entity. Then you can write code to map it accordingly. – dassum Aug 08 '18 at 10:37
  • 1
    There is similar question here on stackoverflow [this may be helpful][1] [1]: https://stackoverflow.com/questions/9741134/how-to-map-json-field-names-to-different-object-field-names – Abdul Fattah Boshi Aug 08 '18 at 10:41
  • @AbdilFattah thank, it is exactly the answer) – catscoolzhyk Aug 08 '18 at 12:16

1 Answers1

1

You can use JsonProperty annotation as below so your clients can send request field name as FIRST_NAME and it can mapped to Employee class :

@Data // comes from lombok
class Employee {
    @JsonProperty("FIRST_NAME")
    private String firstName;

//other fields
}
Emre Savcı
  • 3,034
  • 2
  • 16
  • 25