Despite the success in achieving Java to JSON data transfer using @ResponseBody, implementing its reverse path has been elusive. This article delves into the solution to serialize JSON back into a Java object using @RequestBody.
To ensure a seamless experience, ensure the following:
To illustrate the solution, consider the example below:
web.xml:
<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>
json-servlet.xml:
<beans> <import resource="classpath:mvc-context.xml" /> </beans>
mvc-context.xml:
<beans> <mvc:annotation-driven /> <context:component-scan base-package="test.json" /> </beans>
TestController (controller class):
@Controller @RequestMapping("/test") public class TestController { @RequestMapping(method = RequestMethod.POST, value = "math") @ResponseBody public Result math(@RequestBody final Request request) { ... } }
Request (POJO for POST requests):
public class Request { private int left; private int right; ... }
Result (POJO for serialized responses):
public class Result { private int addition; private int subtraction; private int multiplication; ... }
Execute the command mvn jetty:run and send the following POST request:
The response you should receive:
{"addition":20,"subtraction":6,"multiplication":91}
This demonstrates the bidirectional data transfer between JSON and Java using @RequestBody.
The above is the detailed content of How to Bidirectionally Transfer JSON Data with Spring MVC and jQuery?. For more information, please follow other related articles on the PHP Chinese website!