Spring 3.0使用jackson消息转换器进行JSON响应 [英] Spring 3.0 making JSON response using jackson message converter

查看:682
本文介绍了Spring 3.0使用jackson消息转换器进行JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将我的messageconverter配置为Jackson然后

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>

推荐答案

您需要以下内容:


  1. 设置注释驱动的编程模型:put < mvc:annotation -driven /> in spring.xml

  2. 放置jaskson jar(Maven artifactId org.codehaus.jackson:jackson-mapper-asl )在类路径中。

  3. 使用如下:

  1. Set annotation-driven programming model: put <mvc:annotation-driven /> in spring.xml
  2. Place jaskson jar (Maven artifactId is org.codehaus.jackson:jackson-mapper-asl) in classpath.
  3. Use as the following:

@RequestMapping(method = { RequestMethod.GET, RequestMethod.POST })
public @ResponseBody Foo method(@Valid Request request, BindingResult result){
return new Foo(3,4)
}


这对我有用。

请注意,


  1. @ResponseBody 适用于返回类型,而不是方法定义。

  2. 您需要 @RequestMapping 注释,以便Spring检测它。

  1. @ResponseBody is applied to return type, not to the method definition.
  2. You need @RequestMapping annotation, so that Spring will detect it.

这篇关于Spring 3.0使用jackson消息转换器进行JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆