简体   繁体   English

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

[英]Content type 'application/json' not supported in Spring MVC and jackson

I'm getting an error (Handler execution resulted in exception: Content type 'application/json' not supported) when trying to receive a post request using Spring MVC.尝试使用 Spring MVC 接收发布请求时出现错误(处理程序执行导致异常:不支持内容类型“应用程序/json”)。

My Json, just for testing, is pretty simple:我的 Json,仅用于测试,非常简单:

{ "test": "abc123" }

My pojo class:我的 pojo 课:

public class Request {

    String test;

    public String getTest() {
        return test;
    }

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

}

And my controller:还有我的控制器:

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

In my pom.xml, I added:在我的 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>

I think that something is wrong in json deserialization, but I cannot find it.我认为json反序列化有问题,但我找不到。

Any help is welcome.欢迎任何帮助。 Thanks.谢谢。

Here is my working example: 这是我的工作示例:

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

This project has only 1 dependency: 该项目只有1个依赖项:

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

When I call the url like this: 当我这样调用网址时:

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

I see the correct abc123 in the logs. 我在日志中看到正确的abc123 If I remove Content-type header I get the exception 如果删除Content-type标头,则会出现异常

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

In my case the problem was an addition to a dto of a property which having a type that was error prone for Jackson, it was of type JsonObject. 在我的情况下,问题是属性的dto的添加,该属性的类型对于Jackson来说很容易出错,类型是JsonObject。 Jackson was unable to deserialize other objects because of that addition. 由于添加了杰克逊,因此无法反序列化其他对象。
The exception message is completely inaccurate! 异常消息是完全不正确的!

Add this Bean in your webconfig class 将此Bean添加到您的webconfig类中

@Bean
public ContentNegotiatingViewResolver contentViewResolver() {
    ContentNegotiationManagerFactoryBean contentNegotiationManager = new ContentNegotiationManagerFactoryBean();
    contentNegotiationManager.addMediaType("json", MediaType.APPLICATION_JSON);

    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/jsp/");
    viewResolver.setSuffix(".jsp");

    MappingJackson2JsonView defaultView = new MappingJackson2JsonView();
    defaultView.setExtractValueFromSingleKeyModel(true);

    ContentNegotiatingViewResolver contentViewResolver = new ContentNegotiatingViewResolver();
    contentViewResolver.setContentNegotiationManager(contentNegotiationManager.getObject());
    contentViewResolver.setViewResolvers(Arrays.<ViewResolver> asList(viewResolver));
    contentViewResolver.setDefaultViews(Arrays.<View> asList(defaultView));
    return contentViewResolver;
}

UPDATE UPDATE

The guys from the comments are right, this won't fix your issue but I noticed something. 评论中的人是正确的,这不会解决您的问题,但我注意到了一些问题。

If I set consumes = MediaType.APPLICATION_JSON_VALUE and in the request I don't specify the content type it will throw an exception then if I set the content type the issue is fixed. 如果设置了消耗= MediaType.APPLICATION_JSON_VALUE,并且在请求中我未指定内容类型,则它将引发异常,然后,如果设置了内容类型,则此问题已解决。

Now, the issue seems to be something with your dependencies. 现在,问题似乎与您的依赖性有关。

My pom dependencies: 我的pom依赖项:

 <properties>
     <springframework.version>4.1.9.RELEASE</springframework.version>
     <springframework.security.oauth.version>2.0.9.RELEASE</springframework.security.oauth.version>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

    ...

</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${springframework.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.security.oauth</groupId>
        <artifactId>spring-security-oauth2</artifactId>
        <version>${springframework.security.oauth.version}</version>
    </dependency>

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.3.1</version>
    </dependency>

    ...

</dependencies>

对于寻找此问题的其他任何人,我的Pojo类上必须至少有一个公共变量或吸气剂。

I had same issue. 我有同样的问题。 finally i resolved it. 终于我解决了。 Actual error was in jackson lib. 实际错误出在jackson库。 Here is the location and code snippet. 这是位置和代码段。

/* \.m2\repository\com\fasterxml\jackson\core\jackson-databind\2.6.5\jackson-databind-2.6.5-sources.jar!\com\fasterxml\jackson\databind\DeserializationContext.java  406 */


public boolean hasValueDeserializerFor(JavaType type, AtomicReference<Throwable> cause) {
        try {
            return _cache.hasValueDeserializerFor(this, _factory, type);
        } catch (JsonMappingException e) {
            if (cause != null) {
                cause.set(e);
            }
        } catch (RuntimeException e) {
            if (cause == null) { // earlier behavior
                throw e;
            }
            cause.set(e);
        }
        return false;
    }

For those who use Spring Framework , not Spring Boot, and encounter this problem.对于那些使用Spring Framework而不是Spring Boot 的人,遇到了这个问题。

The root of this problem is:这个问题的根源是:

  • Spring need to ① recognize the "Content-Type", and ② convert the content to the parameter type we declared in the method's signature. Spring需要①识别“Content-Type”,②将内容转换为我们在方法签名中声明的参数类型

  • The ' application/json ' is not supported, because, by default , the Spring cannot find a proper HttpMessageConverter to do the converting job , which is step ②.不支持“ application/json ”,因为默认情况下,Spring 找不到合适的 HttpMessageConverter来完成转换工作,即步骤②。

Solution :解决方案

  • We manually add a proper HttpMessageConverter into the Spring's configuration of our application .我们手动将适当的HttpMessageConverter添加到我们应用程序Spring 配置中。

Steps:脚步:

  1. Choose the HttpMessageConverter's class we want to use.选择我们要使用的HttpMessageConverter 类 For Json, we can choose from "org.springframework.http.converter.json. JsonbHttpMessageConverter ", "org.springframework.http.converter.json. MappingJackson2HttpMessageConverter ", and so on .对于JSON,我们可以从“org.springframework.http.converter.json。JsonbHttpMessageConverter”, “org.springframework.http.converter.json。MappingJackson2HttpMessageConverter”选择,等等

  2. Add the JsonbHttpMessageConverter object (or other kinds of Json HttpMessageConverter object ) to Spring's configuration , by calling the "public void configureMessageConverters (List<HttpMessageConverter<?>> converters)" method of the "WebMvcConfigurer" implementation class in our application.通过在我们的应用程序中调用“WebMvcConfigurer”实现类的“public void configureMessageConverters (List<HttpMessageConverter<?>>converters)”方法,将JsonbHttpMessageConverter对象(或其他类型的Json HttpMessageConverter对象)添加到Spring的配置中 Inside the method, we can add any HttpMessageConverter object as needed, by using " converters.add() ".在方法内部,我们可以根据需要添加任何 HttpMessageConverter 对象,通过使用“ converters.add() ”。

  3. Add correspond dependency into "pom.xml" file.相应的依赖添加到“pom.xml”文件中。 For example, if you use the " JsonbHttpMessageConverter ", then you need to add the dependencies of " javax.json.bind-api " and " yasson ".例如,如果使用“ JsonbHttpMessageConverter ”,则需要添加“ javax.json.bind-api ”和“ yasson ”的依赖项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Spring MVC - 不支持内容类型“应用程序/json” - Spring MVC - Content type 'application/json' not supported POST上的Spring MVC不支持内容类型&#39;application / json&#39; - Content type 'application/json' not supported in Spring MVC on POST spring boot mvc - 不支持内容类型'application / json; charset = UTF-8' - spring boot mvc - Content type 'application/json;charset=UTF-8' not supported Spring WebClient put Mapping:不支持内容类型&#39;application / json&#39; - Spring WebClient put Mapping: Content type 'application/json' not supported Spring MVC 4:“application/json”内容类型设置不正确 - Spring MVC 4: “application/json” Content Type is not being set correctly 不支持获取内容类型“application/json” - Getting Content type 'application/json' not supported Spring Rest 应用程序中的“不支持内容类型‘application/json;charset=UTF-8’” - "Content type 'application/json;charset=UTF-8' not supported" in Spring Rest application 当我尝试将 JSON 发送到 Spring 时,不支持内容类型“application/json;charset=UTF-8” - Content type 'application/json;charset=UTF-8' not supported, when i try send JSON to Spring Spring 启动 controller 调用不支持内容类型 'application/json;charset=UTF-8' - Content type 'application/json;charset=UTF-8' not supported with Spring boot controller call Spring web 客户端返回异常“bodyType=[responseObject] 不支持内容类型‘application/json’ - Spring web client return exception "Content type 'application/json' not supported for bodyType=[responseObject]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM