Monday, May 25, 2015

JSON Jackson custom deserializer to return empty String instead of null

Needed a way to deserialize null values in a JSON as emptry strings (""). This is the shortest I could come with.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.deser.std.UntypedObjectDeserializer;
import com.fasterxml.jackson.databind.module.SimpleModule;
 
public class NullHandlerDeserializer extends UntypedObjectDeserializer {
 
  private static final long serialVersionUID = 1L;
 
  @Override
  public Object deserialize(JsonParser jp, DeserializationContext ctxt)
    throws IOException {
    switch (jp.getCurrentToken()) {
     case VALUE_NULL:     
      return "";
     default:
      return super.deserialize(jp, ctxt);
    }  
  }
 }

The class extends from an existing deserializer implementation to avoid having to code the handling of all JSON tokens. I needed to worry only about VALUE_NULL token.

And to configure the custom deserializer in the ObjectMapper:

1
2
3
4
ObjectMapper om = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(Object.class, new NullHandlerDeserializer());
om.registerModule(module);

No comments:

Post a Comment