Reputation: 85
I'm trying to create a rest post request using Spring but what is been received is a null value.
If I use the first request I get back null values. If I use the second request I receive a 415Unsupported Media Type. Does anyone know where my issue is?
@RequestMapping(value = "/product", method=RequestMethod.POST,produces = "application/json")
@ResponseBody Product addProduct(Product p1) {
System.out.print("Adding product:"+p1.getDescription());
return p1;
}
@RequestMapping(value="/product2", method=RequestMethod.POST, produces = { MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Product greeting(@RequestBody Product p1) {
System.out.print("Adding product:"+p1.getDescription());
return p1;
}
UPDATE to include POSTMAN 1 2 3
Upvotes: 0
Views: 1378
Reputation: 652
Try doing this:
@PostMapping(path = "/product")
public ResponseEntity<Product> addProduct(@RequestBody Product p1) {
System.out.print("Adding product:"+p1.getDescription());
return new ResponseEntity<Product>(p1, HttpStatus.OK);
}
By default, Spring should detect that the JSON you are trying to pass can be parsed into a Product
object. Spring also takes care of the return type, therefore, you don't need to write a lot of code to make the object be parsed back to a JSON.
Also, on Postman, add the header Content-Type
with the value application/json
.
Upvotes: 1