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。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南