Spring 3.0 使用 jackson 消息转换器制作 JSON 响应 [英] Spring 3.0 making JSON response using jackson message converter
问题描述
我将我的 messageconverter 配置为 Jackson's then
i configure my messageconverter as Jackson's then
class Foo{int x; int y}
在控制器中
@ResponseBody
public Foo method(){
return new Foo(3,4)
}
我希望从服务器返回一个 JSON 字符串 {x:'3',y:'4'} 而没有任何其他配置.但是对我的 ajax 请求收到 404 错误响应
from that i m expecting to return a JSON string {x:'3',y:'4'} from server without any other configuration. but getting 404 error response to my ajax request
如果方法被@ResponseBody注解,则返回类型写入响应HTTP主体.返回值将使用 HttpMessageConverters 转换为声明的方法参数类型.
If the method is annotated with @ResponseBody, the return type is written to the response HTTP body. The return value will be converted to the declared method argument type using HttpMessageConverters.
我错了吗?或者我应该使用序列化程序将我的响应对象转换为 Json 字符串,然后将该字符串作为响应返回.(我可以正确地进行字符串响应)还是应该进行一些其他配置?比如为 Foo 类添加注释
Am I wrong ? or should I convert my response Object to Json string myself using serializer and then returning that string as response.(I could make string responses correctly) or should I make some other configurations ? like adding annotations for class Foo
这是我的 conf.xml
here is my conf.xml
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
推荐答案
您需要:
- 设置注解驱动的编程模型:将
<mvc:annotation-driven/>
放入spring.xml
- 将 jaskson jar(Maven artifactId 是
org.codehaus.jackson:jackson-mapper-asl
)放在类路径中. 如下使用:
- Set annotation-driven programming model: put
<mvc:annotation-driven />
inspring.xml
- Place jaskson jar (Maven artifactId is
org.codehaus.jackson:jackson-mapper-asl
) in classpath. Use as the following:
@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody Foo method(@Valid Request request, BindingResult result){
return new Foo(3,4)
}
这对我有用.
请注意,
@ResponseBody
应用于返回类型,而不是方法定义.- 您需要
@RequestMapping
注释,以便 Spring 检测到它.
@ResponseBody
is applied to return type, not to the method definition.- You need
@RequestMapping
annotation, so that Spring will detect it.
这篇关于Spring 3.0 使用 jackson 消息转换器制作 JSON 响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!