Reputation: 745
I'm working with java project using spring REST.
My problem that i could not extract data from request body (which is json) after receive it as enitiy.
for example:
JSON Request Body
{
"firstname": "Rayan",
"lastname": "Cold",
"company_id": 23
}
My Controller maaped method is:
@PostMapping("/employee")
public Employee createEmployee(@RequestBody Employee employee) {
// Here i need to extract the company id from request body
// Long companyId = *something* // how i can extract from request ?
return companiesRepository.findById(companyId).map(company -> {
employee.setCompany(company);
return employeeRepository.save(employee);
}).orElseThrow(() -> new ResourceNotFoundException("Company not found"));
}
I know i can pass company ID as path variable. But i do want it in request body not in URI.
Thanks
Upvotes: 3
Views: 3747
Reputation: 9437
company_id can not be mapped if your Employee class contains companyId.
I guess your company class like:
public class Employee {
private String firstname;
private String lastname;
private Long companyId;
//skip getter setter }
change it to :
public class Employee {
private String firstname;
private String lastname;
@Transient
@JsonProperty("company_id")
private Long companyId;
//skip getter setter }
Upvotes: 2
Reputation: 3894
You can simply take the company id from the object received:
employee.getCompany_id();
Please ensure, your Employee class should be something like below:
public class Employee
{
private String company_id;
private String lastname;
private String firstname;
// getter and setters of all these member fields
}
Name of the variables should be same as the one in JSON or use the appropriate annotations.
Upvotes: 0