@PostMapping("/user")
public String addUser(@RequestBody User user) {
return user.getName();
}If you send this JSON:
{"name":"Alice","age":30}What will be the response?
@PostMapping("/user") public String addUser(@RequestBody User user) { return user.getName(); }
The @RequestBody annotation tells Spring Boot to convert the incoming JSON into a User object. Then, the method returns the name property, which is "Alice".
Only option C uses @RequestBody, which tells Spring Boot to parse JSON from the request body into the Product object.
@PostMapping("/order")
public String createOrder(@RequestBody String order) {
return order;
}When sending JSON, the client gets a 415 Unsupported Media Type error. What is the likely cause?
@PostMapping("/order") public String createOrder(@RequestBody String order) { return order; }
A 415 error occurs because the client did not set Content-Type to application/json. Spring Boot expects the Content-Type header to match the media type of the request body. Using @RequestBody String is valid if the client sends the correct Content-Type header.
public class User {
private String name;
private int age;
// getters and setters
}And this controller method:
@PostMapping("/user")
public String addUser(@RequestBody User user) {
return user.getName() + "," + user.getAge();
}If the JSON sent is:
{"name":"Bob"}What will be the returned string?
@PostMapping("/user") public String addUser(@RequestBody User user) { return user.getName() + "," + user.getAge(); }
Since age is an int primitive, missing JSON field sets it to 0 by default. Name is set to "Bob".
Jackson, used by Spring Boot, needs a default constructor and setters or a constructor with parameters to map JSON fields to Java objects.