Is it possible to convert from JSON to domain obje

2019-08-06 15:19发布

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

3条回答
爱情/是我丢掉的垃圾
2楼-- · 2019-08-06 15:30

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>
查看更多
ゆ 、 Hurt°
3楼-- · 2019-08-06 15:33

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

查看更多
女痞
4楼-- · 2019-08-06 15:45

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) {
...
}
查看更多
登录 后发表回答