无法写入HTTP消息:org.springframework.http.converter.HttpMessageNotWritableException:找不到类型的返回值的转换器:

时间:2017-11-15 18:51:13

标签: spring spring-mvc spring-restcontroller

我正在尝试公开REST服务,但是当我从POSTMAN点击它时,我正在接下来:

警告:无法写入HTTP消息:org.springframework.http.converter.HttpMessageNotWritableException:找不到类型为:class java.util.ArrayList

的返回值的转换器

我在哪里还包含了以下需要的jar文件:

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

这是我的REST控制器代码:

@RestController
@RequestMapping("/MayankAPI")
public class TestRestAPI {
@RequestMapping(value="/sayHello" , method = RequestMethod.POST)
public TestPojo postData(@RequestBody String payload) {
  System.out.println("Hello post"+payload);
  TestPojo payload1=new TestPojo();
  payload1.setStudentName("Jack");
  return payload1;
}
@RequestMapping(value="/sayHello" , method = RequestMethod.GET)
public List<TestPojo> getData(String payload) {
  System.out.println("Hello get"+payload);
  List<TestPojo> payload1=new ArrayList<TestPojo>();
  TestPojo tp = new TestPojo();
  tp.setStudentName("Jack");
  payload1.add(tp);
  return payload1;
}

这是我试图返回的我的bean:

public class TestPojo {

  private String studentName;
  private String studentId;

  public String getStudentName() {
    return studentName;
  }

  public void setStudentName(String studentName) {
    this.studentName = studentName;
  }

  public String getStudentId() {
    return studentId;
  }

  public void setStudentId(String studentId) {
    this.studentId = studentId;
  }
}

请帮助我在哪里做错了。

2 个答案:

答案 0 :(得分:3)

发生这种情况是因为MappingJackson2HttpMessageConverter未在我的App配置文件中注册,如下所示。

@Configuration
@ComponentScan("basePackages = com.test")
public class MiBenefitConfiguration extends WebMvcConfigurationSupport{

  @Bean
  public ObjectMapper getObjectMapper() {
    return new ObjectMapper();
  }

  @Bean
  public MappingJackson2HttpMessageConverter messageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(getObjectMapper());
    return converter;
  }

  @Override
  public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.add(messageConverter());
    addDefaultHttpMessageConverters(converters);
  }
}

答案 1 :(得分:2)

我知道为时已晚,但仍然 替代解决方案: 您需要按以下步骤将Spring项目作为Web MVC启用:

@Configuration @EnableWebMvc @ComponentScan("basePackages = com.test") public class MiBenefitConfiguration { }