Home >Java >javaTutorial >How to Integrate JQuery, Spring MVC\'s @RequestBody, and JSON for Bidirectional Serialization?
While serializing Java objects to JSON for JQuery consumption may be straightforward, the reverse path—parsing JSON and converting it into Java objects—can pose challenges. This article will guide you through the steps necessary to make this bidirectional serialization a reality.
To deserialize JSON into a Java object using Spring MVC @RequestBody, it is essential to register the MappingJacksonHttpMessageConverter. While this can be done manually, the simplest method is to use
Consider the following example, which showcases a complete solution for bidrectional JSON serialization:
<!-- Spring MVC --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency> <!-- Jackson --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.4.2</version> </dependency>
<servlet-mapping> <servlet-name>json</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> #### Spring Bean Configuration
<import resource="classpath:mvc-context.xml" />
#### `mvc-context.xml`
<mvc:annotation-driven /> <context:component-scan base-package="test.json" />
#### Controller
@Controller
@RequestMapping("/test")
public class TestController {
@RequestMapping(method = RequestMethod.POST, value = "math") @ResponseBody public Result math(@RequestBody final Request request) {...}
}
#### Domain Objects
public class Request {
// ... fields and getters/setters ...
}
public class Result {
// ... fields and getters/setters ...
}
#### Testing the Setup Using the Poster Firefox plugin, send a POST request to the following URL:
URL: http://localhost:8080/test/math
mime type: application/json
post body: { "left": 13 , "right" : 7 }
#### Expected Response
{"addition":20,"subtraction":6,"multiplication":91}
The above is the detailed content of How to Integrate JQuery, Spring MVC\'s @RequestBody, and JSON for Bidirectional Serialization?. For more information, please follow other related articles on the PHP Chinese website!