java - Spring 3.0 使用 jackson 消息转换器做出 JSON 响应

我将我的 messageconverter 配置为 Jackson 的 then

class Foo{int x; int y}

在 Controller 中

@ResponseBody
public Foo method(){
   return new Foo(3,4)
}

我希望从服务器返回一个 JSON 字符串 {x:'3',y:'4'} 而无需任何其他配置。但是我的 ajax 请求得到 404 错误响应

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 类添加注解

这是我的 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 />spring.xml
  2. 在类路径中放置 jaskson jar(Maven artifactId 为 org.codehaus.jackson:jackson-mapper-asl)。
  3. 如下使用:

    @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 检测到它。

https://stackoverflow.com/questions/2259551/

相关文章:

json - meteor `Deps.autorun` 与 `Collection.observ

python - 如何在scrapy中实现嵌套项?

c# - 类型是接口(interface)或抽象类,不能实例化

bash - jq 直接替换文件上的文本(如 sed -i)

android - 对等通信选项

json - Jackson JsonTypeInfo.As.EXTERNAL_PROPERTY 无

json - HATEOAS中 "_embedded"的含义及用法

android - 如何从 JSONObject 中删除 nameValuePairs 键?

json - 遍历 JSON 文件 PowerShell

mysql - 如何在 MySQL 中编写可以解析列中 JSON 数据的查询?