在方法或者类上加注解@ResponseBody,则自动返回json或者xml格式数据,可以自己修改配置。如果在返回数据中有JSONObject 或者jsonArray格式数据,就会报如下错误。
org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON document: No serializer found for class org.codehaus.jettison.json.JSONObject and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS
开始我看报错一位是我用的JSONObject jar包没有Serializable,后来换了jettison也不行,再看是disable SerializationFeature.FAIL_ON_EMPTY_BEANS,就是说值有为null,后来把值都初始化了也不行。
再后来,百度查说在配置文件application.properties加上 spring. jackson.serialization.FAIL_ON_EMPTY_BEANS= false, 就是表示忽略null值。这样是不报错,但我实际有值,接口显示没有。 后来我吧JSONObject换成Map<String,Object>. 把jsonArray换成list就好了。再网上查到如下
:https://www.cnblogs.com/qq78292959/p/3760651.html
MappingJacksonHttpMessageConverter 调用了 objectMapper.writeValue(OutputStream stream, Object)方法,使用@ResponseBody注解返回的对象就传入Object参数内。若返回的对象为已经格式化好的json串时,不使用@RequestBody注解,而应该这样处理:
1、response.setContentType("application/json; charset=UTF-8");
2、response.getWriter().print(jsonStr);
直接输出到body区,然后的视图为void。
具体源码还要研究为啥。
网友评论