我想有一个双向的JSON到Java序列化
我正在成功地使用 the Java to JSON to JQuery path...(@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...)
}
我正确地配置了Jackson (它会在输出时序列化),当然,我还将MVC设置为注解驱动
我该如何让它工作呢?这是完全可能的吗?或者Spring / JSON / JQuery是单向的?
更新:
我改变了杰克逊的设置
<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>
对(几乎相似的)建议
<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>
而且它似乎起作用了!我不知道到底是什么成功了,但它确实有效...
发布于 2011-05-06 16:15:13
我很确定你只需要注册MappingJacksonHttpMessageConverter
(最简单的方法是is through in XML or @EnableWebMvc
in Java)
请参阅:
下面是一个有效的示例:
Maven
<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/webapp/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//java/test/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;}
}
Result.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}
发布于 2011-05-06 16:36:38
此外,您还需要确保您拥有
<context:annotation-config/>
在您的SPring配置xml中。
我也推荐你阅读这篇博文。这对我帮助很大。Spring blog - 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 headers插件也可以提供帮助。
发布于 2012-08-12 21:58:47
除了这里的答案。
如果你在客户端使用jquery,这对我很有效:
Java:
@RequestMapping(value = "/ajax/search/sync")
public String sync(@RequestBody Foo json) {
Jquery (需要包含Douglas Crockford的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');
}
});
https://stackoverflow.com/questions/5908466
复制相似问题