【问题标题】:Spring 3.0 making JSON response using jackson message converterSpring 3.0 使用杰克逊消息转换器做出 JSON 响应
【发布时间】:2011-01-16 14:28:38
【问题描述】:

我将我的 messageconverter 配置为 Jackson 的 then

class Foo{int x; int y}

在控制器中

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

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

如果方法带有@ResponseBody 注释,则返回类型将写入响应HTTP 正文。返回值将使用 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>

【问题讨论】:

  • 值得一提的是我不使用视图或模型图我有一个 js UI
  • 现在我将我的对象序列化为字符串并将这些字符串发布到客户端
  • checkout here 如果您要迁移到新的 spring 3.2。

标签: java json spring spring-mvc jackson


【解决方案1】:

您需要以下内容:

  1. 设置注解驱动编程模型:将&lt;mvc:annotation-driven /&gt;放入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会检测到它。

【讨论】:

  • 我认为这里的关键部分是 OP 没有 RequestMapping。正如您所建议的那样,提供这一点很重要。
  • @ResponseBody 应用于返回类型 - 这是我的问题,谢谢!
  • 使用 Curl 测试您的帖子请求或升级到 spring 3.2 checkout here.
  • @ResponseBody 可以放在公共标识符之前或之后。在任何一个地方,它都是方法签名的一部分,与返回类型无关。 (@ResponseBody 是一个@Target(ElementType.METHOD) 注释。)
【解决方案2】:

这对我有用:

@RequestMapping(value = "{p_LocationId}.json", method = RequestMethod.GET)
protected void getLocationAsJson(@PathVariable("p_LocationId") Integer p_LocationId,
     @RequestParam("cid") Integer p_CustomerId, HttpServletResponse response) {
        MappingJacksonHttpMessageConverter jsonConverter = 
                new MappingJacksonHttpMessageConverter();
        Location requestedLocation = new Location(p_LocationId);
        MediaType jsonMimeType = MediaType.APPLICATION_JSON;
        if (jsonConverter.canWrite(requestedLocation.getClass(), jsonMimeType)) {
        try {
            jsonConverter.write(requestedLocation, jsonMimeType,
                                   new ServletServerHttpResponse(response));
            } catch (IOException m_Ioe) {
                // TODO: announce this exception somehow
            } catch (HttpMessageNotWritableException p_Nwe) {
                // TODO: announce this exception somehow
            }
        }
}

请注意,该方法不返回任何内容:MappingJacksonHttpMessageConverter#write() 具有魔力。

【讨论】:

    【解决方案3】:

    MessageConverter 接口http://static.springsource.org/spring/docs/3.0.x/javadoc-api/ 定义了一个 getSupportedMediaTypes() 方法,在 MappingJacksonMessageCoverter 的情况下返回 application/json

    public MappingJacksonHttpMessageConverter() {
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }
    

    我假设缺少 Accept: application/json 请求标头。

    【讨论】:

      【解决方案4】:

      HTTP 404 错误仅表示找不到资源。这可能有两个原因:

      1. 请求 URL 错误(客户端错误或给定链接/按钮中的 URL 错误)。
      2. 资源不在您期望的位置(服务器端错误)。

      要修复 1,请确保您使用或提供了正确的请求 URL(区分大小写!)。要修复 2,请检查服务器启动日志是否有任何启动错误并相应地修复它们。

      这一切都超出了目前发布的代码和信息。

      【讨论】:

      • 嗯,我没有这么简单。但是我的请求是用该方法处理的,正如我之前所说的,我可以返回 String。它也是 ajax 请求,我之前可能会提到。我想一个春天的家伙会得到我的问题谢谢你的回答
      【解决方案5】:

      我发现我也需要jackson-core-asl.jar,而不仅仅是jackson-mapper-asl.jar

      【讨论】:

        【解决方案6】:

        这只是一个猜测,但默认情况下,Jackson 仅自动检测公共字段(和公共 getter;但所有 setter,无论可见性如何)。如果需要,可以配置它(使用版本 1.5)以自动检测私有字段(有关详细信息,请参阅 here)。

        【讨论】:

          【解决方案7】:

          我猜 404 与您的 HttpMessageConverter 无关。我有同样的 404 问题,原因是我忘记了只有匹配 &lt;url-pattern&gt; 的请求才会发送到 DispatcherServlet(我将请求映射从 *.do 更改为 *.json)。也许这也是你的情况。

          【讨论】:

            【解决方案8】:

            除了这里的答案..

            如果您在客户端使用 jquery,这对我有用:

            Java:

            @RequestMapping(value = "/ajax/search/sync") 
            public ModelAndView 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');
                }
            });
            

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2023-04-07
              • 1970-01-01
              • 2012-11-15
              • 1970-01-01
              • 1970-01-01
              • 2015-01-12
              • 2019-05-18
              相关资源
              最近更新 更多