1

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

4

3 回答 3

3

是的。在您的对象之前使用 @RequestBody 注释(http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestbody):

public void jsonMethod(@RequestBody Dog dog)

注意:您必须有 jackson 才能将 json 转换为您的自定义对象。杰克逊行家依赖:

<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.7.1</version>
</dependency>
于 2013-08-16T18:54:08.153 回答
2

像这样定义您的方法签名:

@RequestMapping(value="/jsonRequest")
public @ResponseBody SomeResult jsonHandler(@RequestBody(required=false) Dog dog, 
       @RequestPart(value="part2", required=false) String part2) {
...
}
于 2013-08-16T19:01:47.337 回答
0

是的,你必须使用杰克逊。对传入参数使用 @RequestBody 注释。为 codehous.jackson 添加依赖项。并将 JsonConverter 添加到 spring 上下文文件中

<mvc:annotation-driven>
  <mvc:message-converters>
     <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
   </mvc:message-converters>
</mvc:annotation-driven>

顺便说一句,你可以看看这里的教程。他们使用 JSON 和 Spring MVC:sites.google.com/site/upida4j/example

于 2013-08-16T23:49:26.793 回答