Spring MVC 和 jackson 不支持内容类型“application/json”

ped*_*eis 7 java spring json spring-mvc

尝试使用 Spring MVC 接收发布请求时,出现错误(处理程序执行导致异常:不支持内容类型“application/json”)。

我的 Json 只是用于测试,非常简单:

{ "test": "abc123" }
Run Code Online (Sandbox Code Playgroud)

我的 pojo 类:

public class Request {

    String test;

    public String getTest() {
        return test;
    }

    public void setTest(String test) {
        this.test = test;
    }

}
Run Code Online (Sandbox Code Playgroud)

还有我的控制器:

@RequestMapping(value = "/testing", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
private void testing(@RequestBody Request body, @RequestHeader HttpHeaders headers, HttpServletRequest httpRequest) {
    System.out.println(body.getTest());
}
Run Code Online (Sandbox Code Playgroud)

在我的 pom.xml 中,我添加了:

<dependencies>
    ...
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.7.2</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.8.5</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.dataformat</groupId>
        <artifactId>jackson-dataformat-xml</artifactId>
        <version>2.4.3</version>
    </dependency>
</dependencies>
Run Code Online (Sandbox Code Playgroud)

我认为json反序列化有问题,但我找不到它。

欢迎任何帮助。谢谢。

Geo*_*lou 10

就我而言,问题是添加了一个属性的 dto,该属性的类型对于 Jackson 来说很容易出错,它的类型是 JsonObject。由于这一添加,杰克逊无法反序列化其他对象。
异常消息完全不准确!


Nik*_*kem 2

这是我的工作示例:

@SpringBootApplication
@Controller
public class Application {

  public static void main(String[] args) {
    SpringApplication.run(Application.class);
  }


  @RequestMapping(value = "/testing", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  @ResponseBody
  private void testing(@RequestBody Request body, @RequestHeader HttpHeaders headers, HttpServletRequest httpRequest) {
    System.out.println(body.getTest());
  }
}
Run Code Online (Sandbox Code Playgroud)

该项目只有 1 个依赖项:

org.springframework.boot:spring-boot-starter-web
Run Code Online (Sandbox Code Playgroud)

当我像这样调用 url 时:

curl -XPOST -v -d '{ "test": "abc123" }' -H "Content-type: application/json" http://localhost:8080/testing
Run Code Online (Sandbox Code Playgroud)

abc123在日志中看到正确的内容。如果我删除Content-type标头,我会得到异常

org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded' not supported
Run Code Online (Sandbox Code Playgroud)