I have the following super simple code to test the functionality of a custom serializer in Jackson. For some reason, the module does not register to the ObjectMapper (at least I don't see it register based on the results). Are there any conditions that do not allow a Module to register with ObjectMapper?
import java.io.IOException;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
public class TestJacksonCustomSerializer {
public class TheClass {
public String emptyString = null;
public String[] emptyStringArray= null;
public TheClass() {
}
public String getEmptyString() {
return emptyString;
}
public String[] getEmptyStringArray() {
return emptyStringArray;
}
}
public class NullStringJsonSerializer extends JsonSerializer<String> {
@Override
public void serialize(String string, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
System.out.println("Processing value: " + String.valueOf(string));
if (string == null) jsonGenerator.writeString("");
}
}
public static void main(String[] args) throws Exception {
TestJacksonCustomSerializer testJacksonCustomSerializer = new TestJacksonCustomSerializer();
SimpleModule simpleModule = new SimpleModule();
simpleModule.addSerializer(String.class, testJacksonCustomSerializer.new NullStringJsonSerializer());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(simpleModule);
System.out.println("Number of registered modules: " + String.valueOf(objectMapper.getRegisteredModuleIds().size()));
TheClass theClass = testJacksonCustomSerializer.new TheClass();
System.out.println(objectMapper.writeValueAsString(theClass));
}
}
Output:
Number of registered modules: 0
{"emptyString":null,"emptyStringArray":null}
I am using jackson 2.12.7
Your serializer is not invoked because Jackson determine serializer by type of value, not by type of property. Your value is null
so NullSeriaizer
is used.