springboot~alibaba.fastjson2序列化時過濾字段
當我們使用阿里的alibaba.fastjson2進行json序列化時,你可以通過方法參數PropertyFilter來實現對字段的獲取,將需要序列化的字段寫到PropertyFilter對象里,當然也可以將不進行序列化的寫到這里,進行邏輯非操作即可
實體
class Person {
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
過濾掉字段age,可以使用下面的代碼
public static void main(String[] args) {
Person person = new Person("John", "Doe", 30);
PropertyFilter filter = (source, name, value) -> {
// 過濾掉名為"age"的屬性
return !name.equals("age");
};
String json = JSON.toJSONString(person, filter);
System.out.println(json);
}
alibaba.fastjson要實現,需要自己寫filter了
- 定義filter對象,實現ObjectSerializer 接口
public class ExcludePropertyFilter implements ObjectSerializer {
private final String[] excludeProperties;
public ExcludePropertyFilter(String... excludeProperties) {
this.excludeProperties = excludeProperties;
}
@Override
public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
if (object == null) {
serializer.getWriter().writeNull(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);
return;
}
SerializeWriter out = serializer.getWriter();
out.write('{');
serializer.incrementIndent();
boolean skipComma = true; // 標記是否需要跳過逗號
FieldInfo[] fields = serializer
.getFieldSerializerMap()
.get(object.getClass())
.getFieldInfos();
for (FieldInfo fieldInfo : fields) {
String propertyName = fieldInfo.getName();
boolean exclude = false;
for (String excludeProperty : excludeProperties) {
if (propertyName.equals(excludeProperty)) {
exclude = true;
break;
}
}
if (exclude) {
continue; // 跳過需要排除的屬性
}
if (!skipComma) {
out.write(',');
} else {
skipComma = false;
}
out.writeFieldName(propertyName);
try {
Object propertyValue = fieldInfo.get(object);
serializer.write(propertyValue);
} catch (IllegalAccessException e) {
throw new RuntimeException(e.getMessage(), e);
}
}
serializer.decrementIdent();
serializer.setContext(object, fieldName, features);
out.write('}');
}
}
- 同時過濾掉age字段
public static void main(String[] args) {
Person person = new Person("John", "Doe", 30);
String[] excludeProperties = {"age"};
String json = JSON.toJSONString(person, new ExcludePropertyFilter(excludeProperties));
System.out.println(json);
}
浙公網安備 33010602011771號