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

新手上路,请多包涵

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

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

 { "test": "abc123" }

我的 pojo 类:

 public class Request {

    String test;

    public String getTest() {
        return test;
    }

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

}

还有我的控制器:

 @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());
}

在我的 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>

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

欢迎任何帮助。谢谢。

原文由 pedrohreis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 625
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());
  }
}

该项目只有 1 个依赖项:

 org.springframework.boot:spring-boot-starter-web

当我这样调用 url 时:

 curl -XPOST -v -d '{ "test": "abc123" }' -H "Content-type: application/json" http://localhost:8080/testing

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

org.springframework.web.HttpMediaTypeNotSupportedException","message":"Content type 'application/x-www-form-urlencoded' not supported

原文由 Nikem 发布,翻译遵循 CC BY-SA 3.0 许可协议

在我的例子中,问题是添加了一个属性的 dto,该属性的类型对于 Jackson 来说很容易出错,它是 JsonObject 类型。由于该添加,Jackson 无法反序列化其他对象。

异常消息完全不准确!

原文由 Georgios Syngouroglou 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题