I am doing a multipart request from a JavaScript script (AngularJS) and I get the JSON data as the first part, and an optional file as the second. Is it possible to have the @RequestParam("data") automatically converted from JSON to a class in my application? Like @RequestParam("data") Dog dog
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
Yes. Use @RequestBody annotation before your object (http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestbody):
public void jsonMethod(@RequestBody Dog dog)
Note: you must have jackson to convert json to your custom object. Jackson maven dependency:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
回答2:
Define your method signature like this:
@RequestMapping(value="/jsonRequest")
public @ResponseBody SomeResult jsonHandler(@RequestBody(required=false) Dog dog,
@RequestPart(value="part2", required=false) String part2) {
...
}
回答3:
Yes, you have to use Jackson. Use @RequestBody annotation for incoming parameter. Add dependency for codehous.jackson. And add JsonConverter to spring context file
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
</mvc:message-converters>
</mvc:annotation-driven>
By the way, you can take a look at the tutorial here. they use JSON and spring MVC: sites.google.com/site/upida4j/example