Java 使用 spring-boot-starter-web “找不到可接受的表示”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28466207/
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-11 06:17:37  来源:igfitidea点击:

"Could not find acceptable representation" using spring-boot-starter-web

javajsonspringmavenspring-mvc

提问by crowmagnumb

I am trying to use spring-boot-starter-webto create a rest service serving up JSON representations of Java objects. From what I understand this boot-starter-web jar is supposed to handle the conversion to JSON through Hymanson automatically but I am instead getting this error.

我正在尝试spring-boot-starter-web创建一个休息服务,为 Java 对象的 JSON 表示提供服务。据我了解,这个 boot-starter-web jar 应该通过 Hymanson 自动处理到 JSON 的转换,但我却收到了这个错误。

{ 
  "timestamp": 1423693929568,
  "status": 406,
  "error": "Not Acceptable",
  "exception": "org.springframework.web.HttpMediaTypeNotAcceptableException",
  "message": "Could not find acceptable representation"
}

My Controller is this...

我的控制器是这样的...

@RestController
@RequestMapping(value = "/media")
public class MediaController {
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public @ResponseBody UploadResult test(@RequestParam(value="data") final String data) {
      String value = "hello, test with data [" + data + "]"; 
      return new UploadResult(value);
    }

    @RequestMapping(value = "/test2", method = RequestMethod.POST)
    public int test2() {
        return 42;
    }

    @RequestMapping(value = "/test3", method = RequestMethod.POST)
    public String test3(@RequestParam(value="data") final String data) {
        String value = "hello, test with data [" + data + "]"; 
        UploadResult upload = new UploadResult(value);
        return upload.value;
    }


    public static class UploadResult {
        private String value;
        public UploadResult(final String value)
        {
            this.value = value;
        }
    }
}

My pom.xmlhas...

我的pom.xml有...

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.2.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <version>1.2.1.RELEASE</version>
    <scope>provided</scope>
</dependency>

mvn dependency:treeshows that spring-boot-starter-web does indeed depend on the Hymanson2.4 databind and thus should be on the classpath...

mvn dependency:tree表明 spring-boot-starter-web 确实依赖于 Hymanson2.4 数据绑定,因此应该在类路径上......

[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:1.2.1.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:1.2.1.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:1.2.1.RELEASE:compile
[INFO] |  |  |  +- org.slf4j:jul-to-slf4j:jar:1.7.8:compile
[INFO] |  |  |  \- org.slf4j:log4j-over-slf4j:jar:1.7.8:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.14:runtime
[INFO] |  +- com.fasterxml.Hymanson.core:Hymanson-databind:jar:2.4.4:compile
[INFO] |  |  +- com.fasterxml.Hymanson.core:Hymanson-annotations:jar:2.4.0:compile
[INFO] |  |  \- com.fasterxml.Hymanson.core:Hymanson-core:jar:2.4.4:compile
[INFO] |  +- org.hibernate:hibernate-validator:jar:5.1.3.Final:compile
[INFO] |  |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] |  +- org.springframework:spring-web:jar:4.1.4.RELEASE:compile
[INFO] |  |  +- org.springframework:spring-aop:jar:4.1.4.RELEASE:compile
[INFO] |  |  |  \- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  |  +- org.springframework:spring-beans:jar:4.1.4.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-context:jar:4.1.4.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:4.1.4.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:4.1.4.RELEASE:compile

... yet calling the testservice gives the error mentioned above. test2and test3work fine proving that it must just be the attempted conversion to JSON that is failing? Am I missing some configuration problem or annotations? From all the examples I can find, annotating the class for basic Hymanson JSON conversion is no longer necessary.

...但调用该test服务会出现上述错误。test2并且test3工作正常证明它一定只是尝试转换为失败的 JSON?我是否遗漏了一些配置问题或注释?从我能找到的所有示例中,不再需要为基本的 Hymanson JSON 转换类注释。

Any help greatly appreciated.

非常感谢任何帮助。

采纳答案by ikumen

You have no public getters for your UpdateResult, for example :

您的 UpdateResult 没有公共 getter,例如:

public static class UploadResult {
    private String value;
    public UploadResult(final String value)
    {
        this.value = value;
    }

    public String getValue() {
       return this.value;
    }
}

I believe by default auto discovery is on and will try to discover your getters. You can disable it with @JsonAutoDetect(getterVisibility=Visibility.NONE), and in your example will result in [].

我相信默认情况下自动发现是开启的,并且会尝试发现你的 getter。您可以使用 禁用它@JsonAutoDetect(getterVisibility=Visibility.NONE),在您的示例中将导致[].

回答by wired00

I had a similar error using spring/jhipsterRESTful service (via Postman)

我在使用spring/jhipsterRESTful 服务时遇到了类似的错误(通过Postman

The endpoint was something like:

终点是这样的:

@RequestMapping(value = "/index-entries/{id}",
        method = RequestMethod.GET,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public ResponseEntity<IndexEntry> getIndexEntry(@PathVariable Long id) {

I was attempting to call the restfulendpoint via Postmanwith header Accept: text/plainbut I needed to use Accept: application/json

我试图restful通过Postman标题调用端点,Accept: text/plain但我需要使用Accept: application/json

回答by Gaurav vijayvargiya

Add below dependency to your pom.xml:

将以下依赖项添加到您的pom.xml

<dependency>
    <groupId>com.fasterxml.Hymanson.dataformat</groupId>
    <artifactId>Hymanson-dataformat-xml</artifactId>
    <version>2.10.2</version>
</dependency>

回答by Vasudev

My return object didn't have @XmlRootElement annotation on the class. Adding the annotation solved my issue.

我的返回对象在类上没有 @XmlRootElement 注释。添加注释解决了我的问题。

@XmlRootElement(name = "ReturnObjectClass")
public class ReturnObjectClass {

    @XmlElement(name = "Status", required = true)
    protected StatusType status;
    //...
}

回答by thernandez

I had to explicitly call out the dependency for my json library in my POM.

我必须在我的 POM 中明确调用我的 json 库的依赖项。

Once I added the below dependency, it all worked.

一旦我添加了以下依赖项,一切都奏效了。

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

回答by charlb

If using @FeignClient, add e.g.

如果使用@FeignClient,添加例如

produces = "application/json"

to the @RequestMapping annotation

到@RequestMapping注解

回答by Kranthi Kiran

I too was facing a similar issue. In my case the request path was accepting mail id as path variable, so the uri looked like /some/api/[email protected]

我也面临着类似的问题。在我的情况下,请求路径接受邮件 ID 作为路径变量,所以 uri 看起来像 /some/api/[email protected]

And based on path, Spring determined the uri is to fetch some file with ".com" extension and was trying to use different media type for response then intended one. After making path variable into request param it worked for me.

并且基于路径,Spring 确定 uri 是要获取一些带有“.com”扩展名的文件,并尝试使用不同的媒体类型进行响应,然后是预期的。将路径变量设置为请求参数后,它对我有用。

回答by tom

accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html

接受的答案不适用于 Spring 5。尝试将 Web 服务的 URL 更改为 .json!这是正确的解决方法。这里有很多细节http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html

回答by Dominik H.

I had the same exception but the cause was different and I couldn't find any info on that so I will post it here. It was just a simple to overlook mistake.

我有同样的例外,但原因不同,我找不到任何相关信息,所以我会在这里发布。忽略错误只是一个简单的问题。

Bad:

坏的:

@RestController(value = "/api/connection")

Good:

好的:

@RestController
@RequestMapping(value = "/api/connection")

回答by David Leonardo Bernal

In my case I happened to be using lombok and apparently there are conflicts with the get and set

就我而言,我碰巧正在使用 lombok 并且显然与 get 和 set 存在冲突