使用 @JsonInclude#value = JsonInclude.Include.CUSTOM
并通过 @ JsonInclude#valueFilter
指定一个过滤器类(equals入参为本字段),则该属性值只有在没有被过滤器类过滤的情况下才会被序列化。过滤器类的 equals()
方法用于过滤值;如果返回true,则值不会序列化。
同样,使用 @JsonInclude#content= JsonInclude.Include.CUSTOM
并通过 @JsonInclude#contentFilter
指定过滤器(equals入参为本字段的values),则如果过滤器类的 equals()
方法返回true,则不会序列化目标属性的内容值
package com.jothan.jackson;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;
@Data
public class Employee {
private String name;
@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = DateOfBirthFilter.class)
private Date dateOfBirth;
@JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = PhoneFilter.class)
private Map<String, String> phones;
// 必须静态内部类,否则报找不到无参构造
@NoArgsConstructor
public static class DateOfBirthFilter {
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof Date))
return false;
Date date = (Date) obj;
return !date.before(new Date());
}
}
@NoArgsConstructor
public static class PhoneFilter {
private static Pattern phonePattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");
// 会把 private Map<String, String> phones; 的values当作入参
@Override
public boolean equals(Object obj) {
if (obj == null || !(obj instanceof String))
return false;
return phonePattern.matcher(obj.toString()).matches();
}
}
public static void main(String[] args) throws JsonProcessingException {
Employee employee = new Employee();
employee.setName("Trish");
employee.setDateOfBirth(Date.from(ZonedDateTime.now().plusDays(1).toInstant()));
employee.setPhones(new HashMap<String,String>() {{
put("Cell", "111-111-1111");
put("Work", "(222) 222 2222");
}});
ObjectMapper om = new ObjectMapper();
String jsonString = om.writeValueAsString(employee);
System.out.println(jsonString);
}
}
{"name":"Trish","phones":{"Work":"(222) 222 2222"}}
{"name":"Trish","dateOfBirth":1619091861386,"phones":{"Work":"(222) 222 2222","Cell":"111-111-1111"}}
Jackson JSON - Applying Custom property inclusion rules using @JsonInclude.Include.CUSTOM