转载自: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。