In a Java-based web application using Spring MVC, bidirectional data serialization between JSON and Java objects is sought. The Java-to-JSON path works well, but the reverse path—deserializing JSON input into a Java object through @RequestBody—encounters issues.
To enable bidirectional JSON-Java serialization, it is crucial to register the MappingJacksonHttpMessageConverter in the Spring MVC configuration. This can be achieved in two ways:
Once the message converter is registered, the code shown in the problem description should function as intended.
To demonstrate the working example, a simple web application is provided below:
// ... code @Controller @RequestMapping("/test") public class TestController { @RequestMapping(method = RequestMethod.POST, value = "math") @ResponseBody public Result math(@RequestBody final Request request) { // ... code } } // ... code
<beans xmlns="http://www.springframework.org/schema/beans"...> <mvc:annotation-driven /> <context:component-scan base-package="test.json" /> </beans>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"...> <servlet> <servlet-name>json</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>json</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> </web-app>
To test the application:
The above is the detailed content of How to Enable Bidirectional JSON-Java Serialization with Spring MVC's @RequestBody?. For more information, please follow other related articles on the PHP Chinese website!