Like in other programing languages - python or JS, when we create a rest api specifically post for the request body we attract some JSON Object
EX:
url: .../employee (Post)
request body: {option: {filter: "suman"}}
In Python or JS we can just do request_body.option.filter and get the data
How can I achieve the same with Java ? Do I need need to create a class for the reqeust_body and for option and make an instance object request_body
CodePudding user response:
This depends with other framework elements you use in your application. For example if you bring Spring into the scene, you would be looking to use in built features like dependency injection and support for hibernate (JPA implementation), which depends on the concept of entities that are POJOs with extra annotations. So yes you would need to define entity classes and DTOs for those.
CodePudding user response:
I was able to parse the request body with JSONObject like below
@PostMapping("/customers")
public List<Customer> getCustomerById(@RequestBody Map<String, Object> req) {
// {option: {filter: "alf"}}
JSONObject json = new JSONObject(req);
System.out.println(json.toString(4));
System.out.println(json.getJSONObject("option").get("filter"));
-----------------------
-----------------------
-----------------------
}
Output