Home > Software design >  Can jacksons ObjectMapper serialize Java-null as empty String, in Version 2.11.2
Can jacksons ObjectMapper serialize Java-null as empty String, in Version 2.11.2

Time:07-25

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:

  1. 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));
  1. You can initialise properties with default values on the declaration or in the getter.
  2. 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?

  • Related