tip:首先要对SpirngMVC的工作流程有所了解,可以参考:SpringMVC详细流程
通过了解SpringMVC的工作,我们可以知道在HandlerAdapter调用Handler的时候,首先会通过HttpMessageConverters将Json字符串转换为Java对象,执行完Handler后返回时,也会通过HttpMessageConverters将Java对象转换为Json字符串。我们可以通过实现HttpMessageConverter接口,来完成对Json字符串的处理。
JsonHttpMsgConverter继承FastJsonHttpMessageConverter
FastJsonHttpMessageConverter继承AbstractHttpMessageConverter
AbstractHttpMessageConverter实现HttpMessageConverter
public class JsonHttpMsgConverter extends FastJsonHttpMessageConverter {
@Override
protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
throws IOException, HttpMessageNotWritableException {
JSONObject rs = new JSONObject();
if (obj instanceof Throwable) {
rs.put("success", false);
rs.put("data", obj);
} else {
rs.put("success", true);
rs.put("data", obj);
}
super.writeInternal(rs, outputMessage);
}
}
配置bean
@Bean
public HttpMessageConverters customConverters() {
FastJsonConfig cfg = new FastJsonConfig();
cfg.setCharset(Charset.forName("UTF-8"));
cfg.setDateFormat("yyyy-MM-dd HH:mm:ss");
JsonHttpMsgConverter jsonHttpMsgConverter = new JsonHttpMsgConverter();
jsonHttpMsgConverter.setFastJsonConfig(cfg);
return new HttpMessageConverters(jsonHttpMsgConverter);
}
网友评论