java springboot controller 方法返回内容过滤
下面是一个例子,对当前项目返回的 BigDecimal 类型进行格式化,前提是返回的类型要么是单个实体,要么是可枚举的实体,如果是 Map 或 其它非自定义实体,可能需要再修改一下代码。
@ControllerAdvice public class MyResponseBodyAdvice implements ResponseBodyAdvice<Object> { @Override public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) { return true; } @Override public Object beforeBodyWrite(Object body, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) { if (body != null && body instanceof Result) { var result = (Result) body; var data = result.getData(); if (data != null) { if (data instanceof BigDecimal) result.setData(ReportController.getInstance().formatBigDecimalScore((BigDecimal) data)); else formatBigDecimal(data, 0); } } return body; } public void formatBigDecimal(Object obj, int level) { if (obj == null) { return; } var clazz = obj.getClass(); //System.out.println("formatBigDecimal:" + clazz.getName()); if (clazz.isArray()) { var length = Array.getLength(obj); for (int i = 0; i < length; i++) { formatBigDecimal(Array.get(obj, i), level + 1); } } else if (obj instanceof Iterable<?>) { var iterable = (Iterable<?>) obj; for (Object item : iterable) { formatBigDecimal(item, level + 1); } } else if (clazz.getName().startsWith("net.firstelite.dygl.")) { while (clazz != null) { var fields = clazz.getDeclaredFields(); for (var field : fields) { field.setAccessible(true); try { if (field.get(obj) == null) continue; if (field.get(obj).getClass() == BigDecimal.class) { var val = (BigDecimal) field.get(obj); val = ReportController.getInstance().formatBigDecimalScore(val); field.set(obj, val); } else { formatBigDecimal(field.get(obj), level + 1); } } catch (Exception e) { System.out.println(e.getMessage()); } } clazz = clazz.getSuperclass(); if (clazz == null || !clazz.getName().startsWith("net.firstelite.dygl.")) break; //System.out.println("formatBigDecimal:" + clazz.getName()); } } else { //do nothing } } }
桂棹兮兰桨,击空明兮溯流光。