自定义过滤功能

This commit is contained in:
yuejiajun 2025-09-30 16:02:42 +08:00
parent abf472bcbb
commit beb6b074f7

View File

@ -0,0 +1,74 @@
package com.example.demo.common.filter;
import lombok.extern.slf4j.Slf4j;
import java.util.*;
@Slf4j
public class CustomJsonFilter {
@SuppressWarnings("all")
@Override
public boolean equals(Object obj) {
if (obj == null) {
return true;
}
boolean flag = !shouldInclude(obj);
log.trace("{} => {}", flag, obj);
return flag;
}
/**
* 判断值是否应该被包含
*/
private boolean shouldInclude(Object value) {
// 处理空字符串
if (value instanceof CharSequence) {
return !((CharSequence) value).isEmpty();
}
// 处理空集合
if (value instanceof Collection) {
return !((Collection<?>) value).isEmpty();
}
// 处理空Map
if (value instanceof Map) {
return !((Map<?, ?>) value).isEmpty();
}
// 处理空数组
if (value instanceof Object[]) {
return ((Object[]) value).length > 0;
}
// 处理基本类型数组
if (value instanceof int[]) {
return ((int[]) value).length > 0;
}
if (value instanceof long[]) {
return ((long[]) value).length > 0;
}
if (value instanceof double[]) {
return ((double[]) value).length > 0;
}
if (value instanceof boolean[]) {
return ((boolean[]) value).length > 0;
}
if (value instanceof char[]) {
return ((char[]) value).length > 0;
}
if (value instanceof byte[]) {
return ((byte[]) value).length > 0;
}
if (value instanceof float[]) {
return ((float[]) value).length > 0;
}
// 处理空Optional
if (value instanceof Optional) {
return ((Optional<?>) value).isPresent();
}
// 其他对象类型只要不为null就包含
return true;
}
}