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
78
79
|
package com.fasterxml.jackson.databind.ser;
import java.io.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
public class TestNullSerialization
extends BaseMapTest
{
static class NullSerializer extends JsonSerializer<Object>
{
@Override
public void serialize(Object value, JsonGenerator jgen, SerializerProvider provider)
throws IOException, JsonProcessingException
{
jgen.writeString("foobar");
}
}
static class Bean1 {
public String name = null;
}
static class Bean2 {
public String type = null;
}
static class MyNullProvider extends SerializerProvider
{
public MyNullProvider() { super(); }
public MyNullProvider(MyNullProvider base, SerializationConfig config, SerializerFactory jsf) {
super(base, config, jsf);
}
@Override
public SerializerProvider createInstance(SerializationConfig config, SerializerFactory jsf) {
return new MyNullProvider(this, config, jsf);
}
@Override
public JsonSerializer<Object> findNullValueSerializer(BeanProperty property)
throws JsonMappingException
{
if ("name".equals(property.getName())) {
return new NullSerializer();
}
return super.findNullValueSerializer(property);
}
}
/*
/**********************************************************
/* Test methods
/**********************************************************
*/
public void testSimple() throws Exception
{
assertEquals("null", new ObjectMapper().writeValueAsString(null));
}
public void testOverriddenDefaultNulls() throws Exception
{
SerializerProvider sp = new SerializerProvider.Impl();
sp.setNullValueSerializer(new NullSerializer());
ObjectMapper m = new ObjectMapper();
m.setSerializerProvider(sp);
assertEquals("\"foobar\"", m.writeValueAsString(null));
}
public void testCustomNulls() throws Exception
{
ObjectMapper m = new ObjectMapper();
m.setSerializerProvider(new MyNullProvider());
assertEquals("{\"name\":\"foobar\"}", m.writeValueAsString(new Bean1()));
assertEquals("{\"type\":null}", m.writeValueAsString(new Bean2()));
}
}
|