2011-05-06 53 views
67

我想有一個雙向的JSON到Java序列化了jQuery,Spring MVC的@RequestBody和JSON - 使它共同努力

我使用成功的Java來JSON jQuery的路徑...(@ResponseBody ) 例如

@RequestMapping(value={"/fooBar/{id}"}, method=RequestMethod.GET) 
    public @ResponseBody FooBar getFooBar(
      @PathVariable String id, 
      HttpServletResponse response , ModelMap model) { 
     response.setContentType("application/json"); 
... 
} 

和jQuery中我使用

$.getJSON('fooBar/1', function(data) { 
    //do something 
}); 

這個作品以及(如註釋已經工作,感謝所有的應答者)

但是,我怎麼做反向路徑:使用RequestBody將JSON序列化爲Java對象?

不管我怎麼努力,我不能讓這樣的事情的工作:

@RequestMapping(value={"/fooBar/save"}, method=RequestMethod.POST) 
public String saveFooBar(@RequestBody FooBar fooBar, 
     HttpServletResponse response , ModelMap model) { 

    //This method is never called. (it does when I remove the RequestBody...) 
} 

我有傑克遜正確配置(它系列化的出路),我有MVC設置爲驅動的註解當然

我該如何使它工作?有沒有可能?或者是Spring/JSON/JQuery是單向的(out)?


更新:

我改變了這個傑克遜設置

<bean id="jsonHttpMessageConverter" 
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" /> 

<!-- Bind the return value of the Rest service to the ResponseBody. --> 
<bean 
    class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
    <property name="messageConverters"> 
     <util:list id="beanList"> 
      <ref bean="jsonHttpMessageConverter" /> 
<!--   <ref bean="xmlMessageConverter" /> -->    
     </util:list> 
    </property> 
</bean> 

到了(幾乎similiar一個)建議

<bean id="jacksonMessageConverter" 
    class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 
    <bean 
     class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
     <property name="messageConverters"> 
      <list> 
       <ref bean="jacksonMessageConverter" /> 
      </list> 
     </property> 
    </bean> 

它似乎工作!我不知道這個訣竅究竟是什麼,但它的工作原理是......

+0

我在這裏更好地解釋了這個問題:http://stackoverflow.com/questions/5930894/can-jackson-be-used-with-spring-mvc-3-0-to-also-bind-the-requestbody- (我會關閉這個,因爲它似乎太長,不清楚) – 2011-05-08 23:02:14

+0

它看起來沒有被調用,因爲你正在做一個GET,但你的方法是一個POST。 – egervari 2013-09-29 18:24:06

回答

94

我敢肯定,你只需要註冊MappingJacksonHttpMessageConverter

(最簡單的方法來做到這一點is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java

參見:


這裏有一個工作示例:

Maven的POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging> 
    <version>0.0.1-SNAPSHOT</version><name>json test</name> 
    <dependencies> 
     <dependency><!-- spring mvc --> 
      <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version> 
     </dependency> 
     <dependency><!-- jackson --> 
      <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version> 
     </dependency> 
    </dependencies> 
    <build><plugins> 
      <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId> 
      <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin> 
      <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId> 
      <version>7.4.0.v20110414</version></plugin> 
    </plugins></build> 
</project> 

文件夾中的src/main/web應用/ WEB-INF

的web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" 
    version="2.4"> 
    <servlet><servlet-name>json</servlet-name> 
     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> 
     <load-on-startup>1</load-on-startup> 
    </servlet> 
    <servlet-mapping> 
     <servlet-name>json</servlet-name> 
     <url-pattern>/*</url-pattern> 
    </servlet-mapping> 
</web-app> 

JSON-servlet.xml中

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans.xsd"> 

    <import resource="classpath:mvc-context.xml" /> 

</beans> 

在文件夾中的src /主/資源:

MVC-context.xml中

<beans xmlns="http://www.springframework.org/schema/beans" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd 
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <mvc:annotation-driven /> 
    <context:component-scan base-package="test.json" /> 
</beans> 

在文件夾中的src /主/爪哇/測試/ JSON

TestController.java

@Controller 
@RequestMapping("/test") 
public class TestController { 

    @RequestMapping(method = RequestMethod.POST, value = "math") 
    @ResponseBody 
    public Result math(@RequestBody final Request request) { 
     final Result result = new Result(); 
     result.setAddition(request.getLeft() + request.getRight()); 
     result.setSubtraction(request.getLeft() - request.getRight()); 
     result.setMultiplication(request.getLeft() * request.getRight()); 
     return result; 
    } 

} 

Request.java

public class Request implements Serializable { 
    private static final long serialVersionUID = 1513207428686438208L; 
    private int left; 
    private int right; 
    public int getLeft() {return left;} 
    public void setLeft(int left) {this.left = left;} 
    public int getRight() {return right;} 
    public void setRight(int right) {this.right = right;} 
} 

結果。的java

public class Result implements Serializable { 
    private static final long serialVersionUID = -5054749880960511861L; 
    private int addition; 
    private int subtraction; 
    private int multiplication; 

    public int getAddition() { return addition; } 
    public void setAddition(int addition) { this.addition = addition; } 
    public int getSubtraction() { return subtraction; } 
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; } 
    public int getMultiplication() { return multiplication; } 
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; } 
} 

可以通過在命令行上執行mvn jetty:run,然後發送POST請求測試此設置:

URL:  http://localhost:8080/test/math 
mime type: application/json 
post body: { "left": 13 , "right" : 7 } 

我用Poster Firefox plugin做到這一點。

這裏的反應是什麼樣子:

{"addition":20,"subtraction":6,"multiplication":91} 
+9

或使用''我想。 – Bozho 2011-05-06 08:34:07

+0

我已經有序列化OUT(ResponseBody,我的問題是序列化IN(RequestBody) – 2011-05-08 21:56:59

+0

MappingJacksonHttpMessageConverter已經註冊,但它對我來說只適用於ResponseBody,我該如何使它適用於RequestBody? – 2011-05-08 22:23:14

12

此外你還需要確保你在Spring XML配置有

<context:annotation-config/> 

我也會建議你閱讀這篇博文。這對我幫助很大。 http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/

更新:

剛剛簽在那裏我有@RequestBody正常工作我的工作代碼。 我也有我的配置這個bean:

<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> 
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> 
<property name="messageConverters"> 
    <list> 
    <ref bean="jacksonMessageConverter"/> 
    </list> 
</property> 
</bean> 

可能這將是很好看什麼的Log4j是說。它通常會提供更多信息,根據我的經驗,如果請求的內容類型不是Application/JSON,則@RequestBody將失敗。您可以運行Fiddler 2來測試它,甚至Mozilla Live HTTP頭插件也可以提供幫助。

+0

當然,如果當然,不是問題再次,我有ResponseBody工作,這是RequestBody,不工作,我敢肯定,我失去了一些基本的... – 2011-05-08 22:22:20

+0

沒有額外的錯誤在log4j :(和我haev相同的配置...有沒有工作示例的地方我可以下載和調試差異? – 2011-05-11 02:18:06

+0

我用你的配置,並取代了我幾乎相同的一個,我真的不知道什麼小改變做的伎倆,但它沒有......感謝 – 2011-05-11 02:35:34

5

如果你不想配置信息轉換器自己,你可以使用 @EnableWebMvc or <mvc:annotation-driven />,傑克遜添加到classpath和Spring會給你默認情況下都JSON,XML(和其他幾個轉換器)。此外,您還將獲得其他一些常用的轉換,格式和驗證功能。

+0

老兄謝謝,因爲這個精彩的建議,完全喜歡它 – 2017-06-24 11:55:12

8

除了這裏的答案...

如果您正在使用在客戶端的jQuery,這個工作對我來說:

的Java:

@RequestMapping(value = "/ajax/search/sync") 
public String sync(@RequestBody Foo json) { 

jQuery的(你需要包括道格拉斯克羅克福德的json2.js有JSON.stringify函數):

$.ajax({ 
    type: "post", 
    url: "sync", //your valid url 
    contentType: "application/json", //this is required for spring 3 - ajax to work (at least for me) 
    data: JSON.stringify(jsonobject), //json object or array of json objects 
    success: function(result) { 
     //do nothing 
    }, 
    error: function(){ 
     alert('failure'); 
    } 
}); 
+0

這將工作,因爲你正在做一個POST和原始海報使用GET。 – egervari 2013-09-29 18:24:56

0

如果你是wi在使用JSON 2和Spring 3.2.0的調用中使用Curl來檢查FAQ here。 AnnotationMethodHandlerAdapter已被棄用,並被RequestMappingHandlerAdapter所取代。