对返回数据的每个字段值进行base64编码
程序员文章站
2024-03-24 08:15:58
...
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
public class CommonEncodingUtils {
/**
* * 递归循环json字符串
* * @param object
* * @return
* * @throws Exception
*
*/
public static Object dealWithRecursion(Object object) {
if (object instanceof JSONObject) {
JSONObject jsonObject = (JSONObject) object;
if (isNullObject(jsonObject)) {
return encode("null");
}
Set<String> keySet = jsonObject.keySet();
for (String o : keySet) {
if (jsonObject.get(o) instanceof JSONObject) {
JSONObject ooo = (JSONObject) jsonObject.get(o);
if (isNullObject(ooo)) {
jsonObject.put(o, encode("null"));
} else {
dealWithRecursion(jsonObject.get(o));
}
} else if (jsonObject.get(o) instanceof JSONArray) {
dealWithRecursion(jsonObject.get(o));
} else {
//这里可对时间进行统一处理
jsonObject.put(o, encode(jsonObject.get(o) + ""));
}
}
return jsonObject;
} else if (object instanceof JSONArray) {
List<Object> list = new ArrayList<>();
JSONArray jsonArray = (JSONArray) object;
for (int i = 0; i < jsonArray.size(); i++) {
Object o = jsonArray.get(i);
list.add(dealWithRecursion(o));
}
return list;
} else {
return encode(object + "");
}
}
/**
* 判空
* @param object
* @return
*/
public static boolean isNullObject(Object object) {
return object == null;
}
/**
* 编码算法
* @param value
* @return
*/
public static String encode(String value) {
return value+"123";
}
}
@RestControllerAdvice(basePackages = "com.controller")
public class EncodingResponseBodyAdvice implements ResponseBodyAdvice<Object> {
//返回true则进行拦截
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
@Override
public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
CommonResult commonResult = (CommonResult)o;
Object data = commonResult.getData();
if(data instanceof ArrayList || data instanceof CommonPage){
Object o1 = JSONObject.toJSON(data);
Object o2 = CommonEncodingUtils.dealWithRecursion(o1);
return CommonResult.success(o2);
}
return o;
}
}