Jackson: deserializing null Strings as empty Strings

Viewed 36024

I have the following class, that is mapped by Jackson (simplified version):

public class POI {
    @JsonProperty("name")
    private String name;
}

In some cases the server returns "name": null and I would like to then set name to empty Java String.

Is there any Jackson annotation or should I just check for the null inside my getter and return empty string if the property is null?

5 Answers

Jackson 2.9 actually offers a new mechanism not yet mentioned: use of @JsonSetter for properties, and its equivalent "Config Overrides" for types like String.class. Longer explanation included in

https://medium.com/@cowtowncoder/jackson-2-9-features-b2a19029e9ff

but gist is that you can either mark field (or setter) like so:

@JsonSetter(nulls=Nulls.AS_EMPTY) public String stringValue;

or configure mapper to do the same for all String value properties:

mapper.configOverride(String.class)
 .setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));

both of which would convert incoming null into empty value, which for Strings is "".

This also works for Collections and Maps as expected.

In case you are looking for a global solution for spring boot, you can configure the ObjectMapper

@Configuration
public class JacksonConfiguration {

    @Bean
    public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder mapperBuilder) {
        DefaultSerializerProvider sp = new DefaultSerializerProvider.Impl();
        sp.setNullValueSerializer(new JsonSerializer<Object>() {
            public void serialize(Object value, JsonGenerator jgen,
                                  SerializerProvider provider)
                    throws IOException, JsonProcessingException
            {
                jgen.writeString("");
            }
        });
        ObjectMapper mapper = mapperBuilder.build();
        mapper.setSerializerProvider(sp);
        return mapper;
    }

}
Related