Spring REST: Get JSON data from Request body in addition to entity

Mohammad Ahmad :

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

Golam Mazid sajib :

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 }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=108882&siteId=1