Java Spring 的 Json 没有得到适当的响应解决

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3340050/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 22:26:08  来源:igfitidea点击:

Spring's Json not being resolved with appropriate response

javajsonspringspring-mvcHymanson

提问by ClutchDude

I've tried to have a controller in Spring return a JSON response to no avail using the Hymanson classes as recommended with 3.0. I've got the Hymanson jar files(Hymanson-core-asl-1.5.5.jar & Hymanson-mapper-asl-1.5.5.jar) in my class path of course.

我试图让 Spring 中的控制器使用3.0 推荐的 Hymanson 类返回一个 JSON 响应,但无济于事。当然,我的类路径中有 Hymanson jar 文件(Hymanson-core-asl-1.5.5.jar 和 Hymanson-mapper-asl-1.5.5.jar)。

As for the appconfig.xml entries, I'm not sure I need these. I've put them in there as a last act of desperation before returning to ol' fashion non-json ajax.

至于 appconfig.xml 条目,我不确定我是否需要这些。在返回 ol'fashion 非 json ajax 之前,我已经把它们放在那里作为最后的绝望行为。

In debug, I watch the controller get the request, return the foo and then, in firebug, get a 406.

在调试中,我观察控制器获取请求,返回 foo,然后在 firebug 中获取 406。

The error messages are as follows: From the logger when set to debug: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

错误消息如下:从设置为调试时的记录器:org.springframework.web.HttpMediaTypeNotAcceptableException:找不到可接受的表示

From the response: (406) The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ().

来自响应:(406)此请求标识的资源只能生成具有根据请求“接受”标头()不可接受的特征的响应。

My appconfig.xml is here:

我的 appconfig.xml 在这里:

    <!-- Configures support for @Controllers -->
    <mvc:annotation-driven />

    <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory -->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
  <property name="mediaTypes">
    <map>
      <entry key="html" value="text/html"/>
      <entry key="json" value="application/json"/>
    </map>
  </property>
  <property name="viewResolvers">
    <list>
      <bean class="org.springframework.web.servlet.view.BeanNameViewResolver"/>
      <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
      </bean>
    </list>
  </property>
  <property name="defaultViews">
    <list>
      <bean class="org.springframework.web.servlet.view.json.MappingHymansonJsonView" />
    </list>
  </property>
</bean>
    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basename" value="messages"></property>
    </bean>

My controller

我的控制器

@RequestMapping(value="foo/bar", method=RequestMethod.GET)
public @ResponseBody foo getFoo(@RequestParam String fooId) {
    return new foo(fooId); 
}

On the jsp, where the ajax call is made:

在进行 ajax 调用的 jsp 上:

function addRow() {
  $.getJSON("foo/bar", {
    fooId: 1
  }, function(data) {
    alert("it worked.");
  });
}

Let me know if there's any more info that is needed.

如果需要更多信息,请告诉我。

采纳答案by Bozho

Get rid of all Hymanson beans, and of the json mapping in the negotiating resolver. the mvc:annotation-drivenshould configure everything you need for the Hymanson serialization to work.

摆脱所有 Hymanson bean 以及协商解析器中的 json 映射。对mvc:annotation-driven应配置,你需要为Hyman逊序列化工作的一切。

回答by dark.gixxer

Sending the Accept: application/xml header does not work. But sending Accept: application/json actually works, and Hymanson mapper kicks in. I got rid of my 406 and got my serialized java object in json format with no more config than @ResponseBody and return new MyObject() :) Thanks skaffman for this information, and thanks Bozho for the working header value :D

发送 Accept: application/xml 标头不起作用。但是发送 Accept: application/json 实际上有效,并且 Hymanson mapper 开始了。我摆脱了我的 406 并以 json 格式获取了我的序列化 java 对象,没有比 @ResponseBody 多的配置并返回 new MyObject() :) 感谢 skaffman信息,并感谢 Bozho 的工作标头值:D

回答by Mir3

This question pops up everywhere on the net and I got bitten by it a couple of times. Spring 3.0.6 (and 5 possibly) has some issues in rendering json. Once I changed to 3.1.0.RELEASE version eveyrything worked AS IS. Without any config changes. Things to note is, the return method must have @ResponseBody (as in the example before) and must be in servlet-context.xml or your spring context configuration file.

这个问题在网上随处可见,我被它咬了几次。Spring 3.0.6(可能还有 5)在呈现 json 时存在一些问题。一旦我更改为 3.1.0.RELEASE 版本,一切都按原样运行。无需任何配置更改。需要注意的是,返回方法必须有@ResponseBody(如前面的示例)并且必须在 servlet-context.xml 或您的 spring 上下文配置文件中。

回答by Shahzeb Khan

May be my answer is a bit late, but it may help some one else visiting this question.

可能我的回答有点晚了,但它可能会帮助其他人访问这个问题。

I got my problem resolved by adding

我通过添加解决了我的问题

 hibernate-validator-4.0.2 

and gave me another exception (class not found exception: org.slf4j.LoggerFactory) which i resolved by adding

并给了我另一个异常(类未找到异常:org.slf4j.LoggerFactory),我通过添加解决了

slf4j-api-1.5.6.jar

I hope it will help someone.

我希望它会帮助某人。

回答by user1552854

Also, make sure that you add two Hymanson related jar files.

另外,请确保添加了两个与 Hymanson 相关的 jar 文件。

  • Hymanson-core-asl-1.9.8.jar
  • Hymanson-mapper-asl-1.9.8.jar
  • Hymanson-core-asl-1.9.8.jar
  • Hymanson-mapper-asl-1.9.8.jar

The version can be different.

版本可以不同。

回答by Apokralipsa

I know that this is an old thread, but maybe someone will encounter the same problem as me. I got that exception when migrating an application from Spring 4.0.3.RELEASE to Spring 4.1.0.RELEASE. In my case updating Hymanson from 1.9.x to 2.4.x did the trick.

我知道这是一个旧线程,但也许有人会遇到和我一样的问题。将应用程序从 Spring 4.0.3.RELEASE 迁移到 Spring 4.1.0.RELEASE 时,我遇到了该异常。就我而言,将 Hymanson 从 1.9.x 更新到 2.4.x 就成功了。

回答by David Lotts

  1. Make sure the POJO you return has get()ers, one for each field.
  2. Make sure the appserver (Tomcat) has the libraries even if you are sure your build system (Eclipse/Maven) does.
  1. 确保您返回的 POJO 具有 get()ers,每个字段一个。
  2. 即使您确定您的构建系统 (Eclipse/Maven) 有这些库,也要确保应用服务器 (Tomcat) 有这些库。

I've had this error twice now. Just now I added getters to my pojo. The 406 error went away and I got JSON as expected. I assume that because my fields were package-protected (the default access), it would grab them, but I guess not. For the record, in case it matters, I also made the POJO implement Serializable, toString(), serialVersionUID, no-arg constructor, and explicit constructors.

我现在有两次这个错误。刚才我在我的 pojo 中添加了吸气剂。406 错误消失了,我按预期得到了 JSON。我假设因为我的字段是包保护的(默认访问),它会抓取它们,但我猜不是。为了记录,以防万一,我还使 POJO 实现了 Serializable、toString()、serialVersionUID、无参数构造函数和显式构造函数。

The prior time I cleaned/cleared/refreshed my Tomcat cache and did whatever else to force it to reload. I believe when I added the Hymanson dependencies, it fixed my compile time errors, but since tomcat missed them, at runtime Spring MVC did not discover the Hymanson libraries, and produced the 406 error about unacceptable response type.

之前我清理/清除/刷新了我的 Tomcat 缓存,并做了其他任何事情来强制它重新加载。我相信当我添加 Hymanson 依赖项时,它修复了我的编译时错误,但是由于 tomcat 错过了它们,因此在运行时 Spring MVC 没有发现 Hymanson 库,并产生了关于不可接受的响应类型的 406 错误。

回答by Patrik Bego

I have got same exception when migrating from spring 3.x to spring 4.x.

从 spring 3.x 迁移到 spring 4.x 时,我遇到了同样的异常。

I solved it with updating Hymanson dependencies from

我通过更新 Hymanson 依赖项解决了这个问题

    <dependency>
        <groupId>org.codehaus.Hymanson</groupId>
        <artifactId>Hymanson-mapper-asl</artifactId>
        <version>1.9.13</version>
    </dependency>

to

    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-core</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-databind</artifactId>
        <version>2.5.1</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.Hymanson.core</groupId>
        <artifactId>Hymanson-annotations</artifactId>
        <version>2.5.1</version>
    </dependency>

Nothing else was needed for me.

我不需要其他任何东西。