0

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 enter image description here 2 enter image description here 3

2
  • Please, add http request example Commented May 6, 2020 at 13:23
  • Added HTTP request Commented May 7, 2020 at 1:26

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.