I use the com.fasterxml.jackson.databind.ObjectMapper in jackson-databind 2.11.2 and try to teach him, that he should serialize java properties with null-value to something like this
{ %Key% : "" }
I tried
ObjectMapper MAPPER = new JodaMapper();
DefaultSerializerProvider defaultSerializerProvider = new DefaultSerializerProvider.Impl();
defaultSerializerProvider.setNullValueSerializer(new JsonSerializer<Object>() {
@Override
public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
gen.writeString("bla");
}
});
MAPPER.setSerializerProvider(defaultSerializerProvider);
But the NullValueSerializers serialize-method does not get triggered for any fields.
Has anybody some ideas?
Thank you
CodePudding user response:
I found the solution.... I had
@JsonInclude(JsonInclude.Include.NON_NULL)
at class level in the class that I wanted to serialize. When I remove the annotation I the code above works.
CodePudding user response:
There are a couple of ways to achieve custom null value serialising:
If you want to serialise a null as an empty String, try using this annotation on a property, or setter:
@JsonSetter(nulls=Nulls.AS_EMPTY)
or the same for specific mapper:
MAPPER.configOverride(String.class).setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
- You can initialise properties with default values on the declaration or in the getter.
- As you've already mentioned, by providing a custom serialiser.
I did try your code, and that serialised null value as expected when using an ObjectMapper instead of JodaMapper. Is there any particular reason for using a JodaMapper?