遇到一个 spring boot 的问题想要实现统一结果集输出: 我使用了:ResponseBodyAdvice
但是这边有个问题就是 String 的话:使用 HttpMessageConverter会报类型转换异常,所以这里做了兼容处理
但是问题又来了,前台返回不了处理后的JSON,我debug 发现代码返回来一个modelAndView [Java] 纯文本查看 复制代码 import com.biu.web.R;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
@RestControllerAdvice
public class BiuResponseAdvice implements ResponseBodyAdvice<Object> {
public static final String BIUREQUESTMAPPING = "BIUREQUESTMAPPING";
/**
* 是否是指定
*
* [url=home.php?mod=space&uid=952169]@Param[/url] methodParameter
* @param aClass
* @return
*/
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
// ---------------------------------- 第三步:start ----------------------------------
// 获取 request
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
// 获取 第一步 设置的属性
String attribute = (String) servletRequestAttributes.getRequest().getAttribute(BIUREQUESTMAPPING);
// 如果属性相等就执行 beforeBodyWrite
return BIUREQUESTMAPPING.equals(attribute);
}
/**
* 如果 supports 返回 true 就执行
* 封装 返回体 为 R 类型
*
* @param o
* @param methodParameter
* @param mediaType
* @param aClass
* @param serverHttpRequest
* @param serverHttpResponse
* @return
*/
@SneakyThrows
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
if (methodParameter.getParameterType().equals(String.class)) {
try {
R r = R.OK().DATA(o);
String jsonStr = new ObjectMapper().writeValueAsString(r);
System.out.println(jsonStr);
return jsonStr;
} catch (JsonProcessingException e) {
throw e;
}
} else if (o instanceof R) {
return o;
} else {
return R.OK().DATA(o);
}
// ---------------------------------- 第三步:end ----------------------------------
}
} |