-
Notifications
You must be signed in to change notification settings - Fork 77
/
CustomBeanPropertyWriterTest.java
77 lines (66 loc) · 2.58 KB
/
CustomBeanPropertyWriterTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package tools.jackson.module.blackbird.ser;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import tools.jackson.core.*;
import tools.jackson.databind.*;
import tools.jackson.databind.module.SimpleModule;
import tools.jackson.databind.ser.BeanPropertyWriter;
import tools.jackson.databind.ser.ValueSerializerModifier;
import tools.jackson.module.blackbird.BlackbirdTestBase;
// for [afterburner#52]
public class CustomBeanPropertyWriterTest extends BlackbirdTestBase
{
static class SampleObject {
public String field1;
public Integer field2;
public Integer field3;
protected SampleObject() { }
public SampleObject(String field1, Integer field2, Integer field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
}
static class Only2BeanSerializerModifier extends ValueSerializerModifier {
private static final long serialVersionUID = 1L;
@Override
public List<BeanPropertyWriter> changeProperties(SerializationConfig config, BeanDescription beanDesc, List<BeanPropertyWriter> props)
{
for (int i = 0, len = props.size(); i < len; ++i) {
BeanPropertyWriter w = props.get(i);
if (Integer.class.isAssignableFrom(w.getType().getRawClass())) {
props.set(i, new Only2BeanPropertyWriter(w));
}
}
return props;
}
}
@SuppressWarnings("serial")
static class Only2BeanPropertyWriter extends BeanPropertyWriter
{
protected Only2BeanPropertyWriter(BeanPropertyWriter base) {
super(base);
}
@Override
public void serializeAsProperty(Object bean, JsonGenerator jgen, SerializerProvider prov)
throws Exception
{
Object val = get(bean);
if((val == null || !val.equals(2)) && _nullSerializer == null) {
return;
}
super.serializeAsProperty(bean, jgen, prov);
}
}
public void testCustomPropertyWriter() throws Exception
{
SimpleModule simpleModule = new SimpleModule()
.setSerializerModifier(new Only2BeanSerializerModifier());
ObjectMapper objectMapper = mapperBuilder()
.addModule(simpleModule)
.changeDefaultPropertyInclusion(incl -> incl.withValueInclusion(JsonInclude.Include.NON_NULL))
.build();
assertEquals("{\"field2\":2}",
objectMapper.writeValueAsString(new SampleObject(null, 2, 3)));
}
}