Spring MVC JSON Example

With Spring MVC Framework, its so much easy to map JSON String to Java Objects or convert Java Objects in to JSON string.

Spring MVC JSON Example

This will only take 3 steps to integrate JSON in your web project.

Configure Spring to Use Jackson

Spring 4 has already its own converter for JSON. You just need to add it to your message converters. To use it, go to your dispatcher-servlet.xml or your spring xml configuration and edit your mvc:annotation-driven:

        <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>

Here, we used MappingJackson2HttpMessageConverter as its message converter.

Add Jackson Dependency in pom

Next, we add the jackson dependency in our pom.xml



Take note that we used version 2 of Jackson dependencies.

Configure your RequestMapping

Lastly, just add the produces attribute in your RequestMapping annotation. You can use MediaType.APPLICATION_JSON_VALUE or just the exact String “application/json”. Take a look at the below example:

@RequestMapping(value = "/search", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public List<Results> search(@ModelAttribute("search_form") SearchDto searchDto) {
    List<Results> results = results.getResults(searchDto);
    return results;

And Spring will automatically convert your java objects in to json format. Using Spring MVC Framework makes it easy to develop web applications.

Share this tutorial!