Bidirectional JSON Serialization in Spring MVC: Configuring @RequestBody and @ResponseBody

Dec 03, 2025 · Programming · 12 views · 7.8

Keywords: Spring | MVC | JSON | RequestBody | Jackson | Serialization

Abstract: This article explores the implementation of bidirectional JSON serialization in the Spring MVC framework, addressing common configuration issues with the @RequestBody annotation. It provides a comprehensive guide, including setup examples and code snippets, to ensure proper integration of Jackson for seamless JSON-to-Java deserialization, and highlights best practices using <mvc:annotation-driven /> for simplified configuration.

Introduction

In web development, JSON serves as a lightweight data interchange format widely used for frontend-backend communication. The Spring MVC framework provides native support for JSON serialization through annotations such as @ResponseBody and @RequestBody. However, users often encounter configuration issues when using @RequestBody for JSON-to-Java deserialization, as seen in the Q&A data where serialization from Java to JSON works, but the reverse path fails.

Problem Analysis

Based on the Q&A data, when using @ResponseBody, Spring MVC correctly serializes Java objects to JSON and returns them to the frontend, for instance via JQuery's $.getJSON calls. However, when using @RequestBody to receive JSON data, such as in a @RequestMapping method with @RequestBody FooBar fooBar, the method is not invoked, indicating that Spring MVC fails to parse the JSON data in the request body. The root cause is the lack of proper message converter configuration.

Solution

The core solution is to register the MappingJacksonHttpMessageConverter, which handles the serialization and deserialization of JSON data. Spring MVC offers a straightforward way to achieve this: use <mvc:annotation-driven /> in XML configuration or the @EnableWebMvc annotation in Java configuration. This automatically registers necessary converters, including JSON support, eliminating the need for manual bean list setup. In the Q&A data, the user resolved the issue by updating the configuration from an explicit bean list to a similar setup, highlighting the convenience of <mvc:annotation-driven />.

Code Implementation

Here is a complete example demonstrating how to configure Spring MVC for bidirectional JSON serialization. First, add configuration in mvc-context.xml:

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="...">
    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

Then, create a controller class using @RequestBody and @ResponseBody annotations:

@Controller
@RequestMapping("/test")
public class TestController {
    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }
}

Define the entity classes as follows:

public class Request implements Serializable {
    private int left;
    private int right;
    // getters and setters
    public int getLeft() { return left; }
    public void setLeft(int left) { this.left = left; }
    public int getRight() { return right; }
    public void setRight(int right) { this.right = right; }
}

The result class is similar, containing computation fields. In the Maven POM, add Spring MVC and Jackson dependencies:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.0.5.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.4.2</version>
</dependency>

Testing Method

To verify the bidirectional serialization, use tools like the Poster Firefox plugin to send POST requests. For example, after starting the application, send a request to http://localhost:8080/test/math with content type application/json and request body { "left": 13, "right": 7 }. The expected response is JSON formatted: {"addition":20,"subtraction":6,"multiplication":91}. This confirms that @RequestBody successfully deserializes JSON to Java objects, and @ResponseBody serializes the result back to JSON.

Conclusion

By correctly configuring the MappingJacksonHttpMessageConverter, Spring MVC can seamlessly support bidirectional JSON serialization. Using <mvc:annotation-driven /> or @EnableWebMvc simplifies configuration, avoiding the complexity of manual converter registration. This case emphasizes the importance of ensuring proper message converter integration in Spring MVC projects for efficient collaboration between @RequestBody and @ResponseBody.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.