import java.util.Arrays;
import java.util.List;
import org.springframework.util.ReflectionUtils;
import com.fasterxml.jackson.annotation.JsonFilter;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.PropertyWriter;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;
public class LogJsonFilter extends SimpleBeanPropertyFilter {
static final List<String> maskingTtargetNames = Arrays.asList("number");
static final List<String> exceptTtargetNames = Arrays.asList("price");
@Override
public void serializeAsField(Object target, JsonGenerator jgen, SerializerProvider provider, PropertyWriter writer)
throws Exception {
String name = writer.getName();
boolean isTarget = false;
if (maskingTtargetNames.contains(name)) {
if (target instanceof String) {
super.serializeAsField(FormatUtil.getSecurity(String.valueOf(target)), jgen, provider, writer);
isTarget = true;
} else {
Field field = ReflectionUtils.findField(target.getClass(), name);
if (field != null) {
boolean orgAccessible = field.isAccessible();
field.setAccessible(true);
Object value = ReflectionUtils.getField(field, target);
if (value instanceof String) {
jgen.writeFieldName(name);
jgen.writeString(FormatUtil.getSecurity(String.valueOf(value)));
isTarget = true;
}
field.setAccessible(orgAccessible);
}
}
} else if (exceptTtargetNames.contains(name)) {
isTarget = true;
}
if (!isTarget) {
super.serializeAsField(target, jgen, provider, writer);
}
}
public static FilterProvider getFilter() {
SimpleFilterProvider simpleFilterProvider = new SimpleFilterProvider();
FilterProvider filters = simpleFilterProvider.setDefaultFilter(new LogJsonFilter());
return filters;
}
@JsonFilter("classFilter")
public class ClassMixIn {
}
public static void main(String[] args) throws JsonProcessingException {
Car car = new Car();
car.setNumber("18다0210");
car.setColor("Red");
car.setPrice("1억9천만원");
ObjectMapper mapper = new ObjectMapper();
mapper.addMixIn(Object.class, ClassMixIn.class);
System.out.println("--필터적용--");
System.out.println(mapper.writer(LogJsonFilter.getFilter()).writeValueAsString(car));
System.out.println("");
mapper = new ObjectMapper();
System.out.println("--필터없이--");
System.out.println(mapper.writer().writeValueAsString(car));
}
static class Car {
private String number;
private String color;
private String price;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
}