java.lang.IllegalArgumentException:找不到类型返回值的转换器

Mar*_*arc 73 java spring jackson spring-boot

有了这段代码

@RequestMapping(value = "/bar/foo", method = RequestMethod.GET)
    public ResponseEntity<foo> foo() {

        Foo model;
        ...
        return ResponseEntity.ok(model);
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到以下异常

java.lang.IllegalArgumentException: No converter found for return value of type
Run Code Online (Sandbox Code Playgroud)

我的猜测是,由于杰克逊失踪,该对象无法转换为JSON.我不明白为什么,因为我认为杰克逊是用春季靴子建造的.

然后我试图将Jackson添加到pom.xml但我仍然有同样的错误

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.4.3</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.4.3</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

我是否必须更改任何弹簧启动属性才能使其正常工作?

谢谢

Mar*_*arc 212

问题是Foo中的一个嵌套对象没有任何嵌套对象 getter/setter

  • 它只需要吸气剂 (3认同)
  • 这也解决了我的问题.如果有人继续收到转换器错误,最可能的原因是杰克逊无法找到/处理必要的吸气剂.仔细检查你的POJO吸气剂!在我的情况下,我在一个属性上有一个低级的getter而不是预期的camel情况:getmetaTag()而不是getMetaTag() (3认同)
  • 我也发生了同样的事情,这挽救了我的生命:) (2认同)
  • 感谢您的回答有帮助,但就我而言,我有两个相同的 json 属性名称分配给两个单独的字段。即@JsonProperty(“id”)...@JsonProperty(“id”)。看起来只要杰克逊序列化器失败就会抛出这个错误。 (2认同)

PAA*_*PAA 18

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

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.1</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

  • Spring Boot Web Starter默认包含Jackson依赖项。 (2认同)
  • 我认为@heemin是对的,我们在使用spring boot时不需要单独依赖jackson-databing。谢谢 (2认同)

Sou*_*ain 11

在错误消息中提到的bean中添加缺少的getter / setter。


Sky*_*ker 9

使用@ResponseBodygetter/setter.希望它能解决你的问题.

@RequestMapping(value = "/bar/foo", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<foo> foo() {
Run Code Online (Sandbox Code Playgroud)

并更新你的mvc-dispatcher-servlet.xml:

<mvc:annotation-driven>
     <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
            <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
   </mvc:message-converters>
</mvc:annotation-driven>
Run Code Online (Sandbox Code Playgroud)

  • 添加“MappingJackson2HttpMessageConverter”对我有用。谢啦。我正在使用 Spring 4.2.5 并面临这个问题。我在 WebMvcConfigurerAdapter 中添加了上面的转换器。 (2认同)

vis*_*213 5

这个问题发生在我的例子中,因为 spring 框架无法获取嵌套对象的属性。Getters/Setters 是一种解决方法。公开属性是另一种快速而肮脏的解决方案,以验证这是否确实是问题所在。


use*_*486 5

配置类上的 @EnableWebMvc 注释解决了我的问题。(Spring 5,无web.xml,由AbstractAnnotationConfigDispatcherServletInitializer初始化)


Yub*_*raj 5

@Marc 写的答案也是有效的。但具体的答案是Getter方法是必需的。你甚至不需要一个Setter.