SpringBoot:HttpMessageNotWritableException: No converter found for return value of type

网上搜了一圈,总结一下出现上述问题的主要原因:

  1. 未写报错的类相应属性的:setter、getter
  2. 缺少jackson包支撑:类对象 -> Json数据格式的转换

对于1中出现的问题,请仔细检查一下对应类属性的:setter和getter是否写完整。
对于2中出现的问题,可在pom.xml中加入包依赖:

<dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.9.1version>
dependency>

<dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-coreartifactId>
        <version>2.9.1version>
 dependency>
 
 <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-annotationsartifactId>
        <version>2.9.1version>
 dependency>

若配置上述jackson包依旧不行,可再加入一个配置类:

import java.util.List;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
@ComponentScan("basePackages = your JavaBean's Package")
public class MiBenefitConfiguration extends WebMvcConfigurationSupport{

  //ObjectMapper这个类是jackson提供的,主要是用来把对象转换成为一个json字符串返回到前端
  //参考链接:https://blog.csdn.net/zxc_user/article/details/79713586
  @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);
  }
}

小结:上述问题困扰了我好几天,最终在:stack overflow上找到了答案,下次碰到类似的问题还是直接上英文网站搜答案比较好。

下面附上stack overflow的答案:
SpringBoot:HttpMessageNotWritableException: No converter found for return value of type_第1张图片

你可能感兴趣的:(JAVA)