在使用jackson时报错:java.lang.IllegalArgumentException: No converter found for return value of type: class X.X.X。
错误原因:
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL) 由于项目中使用了这个注解
这是注解是spring MVC 3.X 支持注解,在需要序列化为json输出的类上增加的,我的spring版本是4.2.4所以报错。
修改方法:
1. springmvc.xml中添加代码:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter" />
jackson1.x版本使用-->
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/><bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/plain; charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</list>
</property>
</bean>
或者 添加下面这个(我项目中使用的):
<mvc:annotation-driven />
2. 导入jar包:
3. 相关类上使用注解(我这里使用的是dto封装的一个类):
我这里使用了两个相关的注解:
@JsonInclude(JsonInclude.Include.NON_NULL)
作用:返回给前端的json中忽略为null的相关数据
@JsonIgnore
作用:返回给前端的json中忽略相关的属性
在class上使用
在属性上使用
引入的jar包是:
通过以上修改测试成功返回json。
知识点总结:
1.spring版本,3.x和4.x的jackson包不一样
spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
2. jackson使用时1.x和2.x的包对应的spring版本不一样,1.x对应spring3.x,2.x对应spring4.x
相关链接:http://blog.youkuaiyun.com/sinat_26630143/article/details/77451801
http://blog.youkuaiyun.com/limm33/article/details/52811499
http://blog.youkuaiyun.com/vili_sky/article/details/73105550