简体   繁体   中英

How to deserialize empty string as a null value in java?

I am coming to a problem where I am trying to deserialize empty string as null value with my code below. is there a way to deserialize it properly. I created a class EmptyStringDeserializer but I got stuck creating the custom deserializer. Below you can find my EmptyStringDeserializer to see what I did wrong.

You could enable ACCEPT_EMPTY_STRING_AS_NULL_OBJECT in your ObjectMapper :

ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

Alternatively, you could define a custom deserializer:

public class CustomStringDeserializer extends JsonDeserializer<String> {

    @Override
    public String deserialize(JsonParser p, DeserializationContext ctxt) 
            throws IOException {

        String value = StringDeserializer.instance.deserialize(p, ctxt);
        if (value == null || value.trim().isEmpty()) {
            return null;
        }

        return value;
    }
}

And register it to a module in your ObjectMapper :

SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new CustomStringDeserializer());

ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);

This deserializer will be used to deserialize all strings.

Your @JsonDeserialize should be on field level not on class level. Add on every String field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM