2

I created custom JsonDeserializer for that can be applied to any field with type String.

public class EmptyToNullStringDeserializer extends JsonDeserializer<String> {
    @Override
    public String deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        String text = jp.getText();
        return "" == text ? null : text;
    }
}

It can be used in models.

class SomeClass {
    @JsonDeserialize(using = EmptyToNullStringDeserializer.class)
    private String someField;
}

It converts JSON

{"someField": ""}

into Java object where someField equals to null (not "")

Question: How to create generic JsonDeserializer that sets null to all Java object fields that equals to "" in JSON? It should be used as:

@JsonDeserialize(using = EmptyToNullStringDeserializer.class)
class SomeClass {
        private String someField;
}

2 Answers 2

1

This more of a Jackson question than a Spring question. You would just need to register your custom deserializer with the ObjectMapper...

SimpleModule module = new SimpleModule("MyModule", new Version(1, 0, 0, null));
module.addDeserializer(String.class, new EmptyToNullStringDeserializer());
mapper.registerModule(module);

How you get access to that ObjectMapper depends on if you are using Spring Boot or just plain Spring.

Sign up to request clarification or add additional context in comments.

Comments

1

You need to register your custom deserializer with ObjectMapper

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.