Controller返回值JSON串化失败,HttpMessageNotWritableException异常解决办法
最近,某同事遇到如下怪异问题,程序变异没问题,启动没问题,从controller调用到service,service里的方法正常返回,controller也能正常接收返回参数,但controller将返回参数json化后,返回给前端的时候,报异常了。
具体错误信息如下:
异常类 → "exception":"org.springframework.http.converter.HttpMessageNotWritableException"
详细异常错误信息 → "message":"Could not write content: No serializer found for class cn.*.*.search.dto.SearchedNotice and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: cn.*.*.*.notice.search.dto.OilPaging[\"articles\"]->java.util.ArrayList[0]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class
最根本原因 → nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class
JSON化失败原因 → to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS
原因已经很明确了,OilPaging该DTO类有的属性是null,导致json化得时候,fasterxml -jackson 将对象转换为json时报错了。
解决方法很简单,找到无法json化的对象,在可能为空的字段上设置@JsonSerialize(include=Inclusion.NON_EMPTY)
意思就是:加入该属性为null,则忽略。