Jackson - accept empty string on Object property

Viewed 3887

I have POJO like this

@Data
public class Tree {
   String id;
   Leaf leaf;
}

How to make, that my rest controller with RequestBody "Tree" will accept JSON request with empty String on property leaf, omitted it and treat as null. Example JSON Request

 {
      "id": "foo",
      "leaf": ""
 }
3 Answers

You have to set the ACCEPT_EMPTY_STRING_AS_NULL_OBJECT attribute of your ObjectMapper to true.

See the documentation :

Determines whether empty String value is accepted as null value for regular POJOs ("beans") with data-binding: this can be useful when dealing endpoints written in a language that has loose typing and may represent missing objects as Empty Strings.

If you're using Spring Boot, you can find details here on how to configure your ObjectMapper.

Configure the ObjectMapper as follows:

ObjectMapper om = new ObjectMapper();
om.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);

You need to configure Jackson ObjectMapper to accept empty string as null. To do that simply add the following method in your configuration class.

@Bean
public ObjectMapper mapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
    return mapper;
}
Related