简体   繁体   English

是否可以使用@RequestParam从JSON转换为域对象

[英]Is it possible to convert from JSON to domain object with @RequestParam

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. 我正在从JavaScript脚本(AngularJS)进行多部分请求,并且将JSON数据作为第一部分,并将可选文件作为第二部分。 Is it possible to have the @RequestParam("data") automatically converted from JSON to a class in my application? 是否可以将@RequestParam(“ data”)从JSON自动转换为应用程序中的类? Like @RequestParam("data") Dog dog 就像@RequestParam("data") Dog dog

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 ): 在对象之前使用@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)

Note: you must have jackson to convert json to your custom object. 注意:您必须具有杰克逊才能将json转换为自定义对象。 Jackson maven dependency: 杰克逊行家依赖:

<dependency>
   <groupId>org.codehaus.jackson</groupId>
   <artifactId>jackson-mapper-asl</artifactId>
   <version>1.7.1</version>
</dependency>

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) {
...
}

Yes, you have to use Jackson. 是的,您必须使用Jackson。 Use @RequestBody annotation for incoming parameter. 对传入参数使用@RequestBody批注。 Add dependency for codehous.jackson. 为codehous.jackson添加依赖项。 And add JsonConverter to spring context file 并将JsonConverter添加到spring上下文文件

<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 他们使用JSON和spring MVC: sites.google.com/site/upida4j/example

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM