By default, when an endpoint expects a JSON document as input and a given controller method argument is annotated with @RequestBody
, Spring will use Jackson databind features to map the incoming JSON document to a Java object. You don't need to use the Jackson's ObjectMapper
directly, as Spring does it for you.
For example purposes, consider the following HTTP request to create a comment:
POST /comments HTTP/1.1
Host: example.org
Content-Type: application/json
{
"content": "Lorem ipsum"
}
And the following class which represents a comment:
@Data
public class Comment {
private String content;
}
A @RestController
to handle such request would be like:
@RestController
@RequestMapping("/comments")
public class CommentController {
@PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Foo> createComment(@RequestBody Comment comment) {
// By default, Spring will rely on Jackson databind to map the incoming
// JSON document to the comment argument annotated with @RequestBody
...
}
}
If you are interested in the Spring component that maps the incoming JSON document to a Java object, have a look at the MappingJackson2HttpMessageConverter
class:
Implementation of HttpMessageConverter
that can read and write JSON using Jackson 2.x's ObjectMapper
.
This converter can be used to bind to typed beans, or untyped HashMap
instances.
By default, this converter supports application/json
and application/*+json
with UTF-8 character set. [...]
If you are creating a HTTP API and exposing resources that can be manipulated with JSON representations, it's unlikely you'll use @ModelAtribute
. Such annotation is particularly useful when you are dealing with web views.