Spring MVC 解决 Could not write JSON: No serializer found for class java.lang.Object
意思是没有找到可用于Object的序列化器,也没有找到属性去创建BeanSerializer。
后面的接着提示了解决方法:(to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)
{
"success": false,
"message": "Could not write JSON: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.xxx.xxx.kbase.common.ResultResponse[\"data\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class java.lang.Object and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) ) (through reference chain: com.xxx.xxx.kbase.common.ResultResponse[\"data\"])"
}
问题是返回实体的data参数中返回了new Object()
controller如下:
@ResponseBody
@RequestMapping(value = "/doc", method = RequestMethod.PUT)
public ResultResponse addDocument(@RequestBody @Valid DocContent docContent) {
ResultResponse resultResponse = new ResultResponse();
esService.addDocument(docContent);
resultResponse.setSuccess(true);
resultResponse.setMessage("ok");
resultResponse.setData(new Object());
return resultResponse;
}
SpringMVC 默认是使用的Jackson序列化
两种解决办法
1,设置Jackson,关掉FAIL_ON_EMPTY_BEANS
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
@Component
public class ObjectMapperConfiguration {
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper().disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
}
2,设置默认序列化为fastjson
// 设置序列化为fastjson
// @Bean
// 使用@Bean注入fastJsonHttpMessageConvert
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1.需要定义一个Convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2.添加fastjson的配置信息,比如是否要格式化返回的json数据
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3.在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
参考:
十七、springboot配置FastJson为Spring Boot默认JSON解析框架(设置默认序列化为fastjson)
关闭spring boot jackson的FAIL_ON_EMPTY_BEANS(设置Jackson)
网友评论