SpringMVC返回对象类型报错HttpMessageNotWritableException No converter found for return value of type

SpringMVC返回对象类型报错HttpMessageNotWritableException: No converter found for return value of type

在使用springMVC前段后端传json数据的时候显示如下异常:

[WARN ] 2018-07-16 19:00:20 org.springframework.web.servlet.mvc.support.DefaultHandlerException
Resolver Failed to write HTTP message: org.springframework.http.
converter.HttpMessageNotWritableException: No converter found for 
return value of type: class com.xxx...

原因就是,springmvc无法将对象直接转换为json对象,这时候,就需要我们来做配置,让springmvc在返回之前,先转换为json。

1、首先需要添加依赖:

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

2、接着在spring-mvc.xml配置文件中添加如下配置(使用jackson不需要以下配置)

<mvc:annotation-driven>
    <!-- 安装FastJson,转换器 -->
    <mvc:message-converters>
        <!-- 选择相应的json解析器 -->
        <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
            <!-- 声明转换类型:json -->
            <property name="supportedMediaTypes">
                <list>
                    <value>application/json</value>
                </list>
            </property>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

注: 使用Jackson的话只要导入依赖就可以使用,因为springMVC默认支持jackson, 如果使FastJson/Gson,则需要第二步手动配置: 至此,No converter found for return value of type报错问题解决。

补充一点:返回的对象中,如果不必要的字段不反回,可以通过@JsonIgnoreProperties来过滤,如果需要返回,一定要确保返回的字段有set,get方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值