zoukankan      html  css  js  c++  java
  • SpringMVC返回对象类型报错HttpMessageNotWritableException: No converter found for return value of type

    转载自:https://blog.csdn.net/feinifi/article/details/81070108

    通常情况下,我们在用springmvc时,会直接返回查询到的分页对象。这时候,如果不做默认配置,会报出如题所示的错误:

    [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.springsecurity.common.Pager

    错因:springmvc无法将对象直接转换为json对象,即使加了@ResponseBody注解。springmvc需要借助第三方转json,可以借助jackson来进行json转换的,所以没有jackson的依赖和相关配置就导致报出了这个错误。

    这时候,就需要我们来做配置,让springmvc在返回之前,先转换为json。

    首先需要添加依赖:

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

    接着在spring-mvc.xml配置文件中添加如下配置,指定Message对象转换器:

    <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>

    至此,No converter found for return value of type报错问题解决。

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

    springmvc需要借助第三方转json,可以借助jackson来进行json转换的,手动转换的话可以考虑fastjson,你如果用过springboot你会发现,他默认就是使用了jackson来转的,他的依赖里面自动包含了jackson。

  • 相关阅读:
    Android复习(五)设备兼容—>多apk支持
    Android复习(五)设备兼容—>支持刘海屏
    KVC给只读属性进行赋值..
    pods 终端安装 第三方框架的一些命令
    使用SnakeKit怎么设置动画效果 以及 UIView的弹簧动画效果
    Cocoa、Foundation、UIKit、Objective-c、XCode、Interface Builder的概念
    仿写SDWebImage中的一个网络加载图片的框架
    TCP/IP 短链接 长链接 scoket
    init 和 initWithFrame 区别
    JSON XML 数据解析
  • 原文地址:https://www.cnblogs.com/FengZeng666/p/14352255.html
Copyright © 2011-2022 走看看