How to deserialize a blank JSON string value to null for java.lang.String?
Jackson will give you null for other objects, but for String it will give empty String.
But you can use a Custom JsonDeserializer
to do this:
class CustomDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser, DeserializationContext context) throws IOException, JsonProcessingException {
JsonNode node = jsonParser.readValueAsTree();
if (node.asText().isEmpty()) {
return null;
}
return node.toString();
}
}
In class you have to use it for location field:
class EventBean {
public Long eventId;
public String title;
@JsonDeserialize(using = CustomDeserializer.class)
public String location;
}
Jackson Deserialization of all empty Strings to null in class
Define a serializer as follows:
public class EmptyStringAsNullDeserializer extends JsonDeserializer<String> {
@Override
public String deserialize(JsonParser jsonParser,
DeserializationContext deserializationContext)
throws IOException {
String value = jsonParser.getText();
if (value == null || value.isEmpty()) {
return null;
} else {
return value;
}
}
}
Add it to a Module
and then register the Module
to your ObjectMapper
:
SimpleModule module = new SimpleModule();
module.addDeserializer(String.class, new EmptyStringAsNullDeserializer());
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(module);
Jackson: deserializing null Strings as empty Strings
You can either set it in the default constructor, or on declaration:
public class POI {
@JsonProperty("name")
private String name;
public POI() {
name = "";
}
}
OR
public class POI {
@JsonProperty("name")
private String name = "";
}
Related Topics
Remove Last Character of a Stringbuilder
How to Pass Console Arguments to Application in Eclipse
What's the Difference Between a Resource, Uri, Url, Path and File in Java
Why Does Java Switch on Contiguous Ints Appear to Run Faster with Added Cases
Resize a Picture to Fit a Jlabel
How to Get Java Logging Output to Appear on a Single Line
Java:Does Wait() Release Lock from Synchronized Block
How to Convert .Pfx File to Keystore with Private Key
Comparing Boxed Long Values 127 and 128
Java 8 Stream with Batch Processing
How an Object Will Call Tostring Method Implicitly
Fixedthreadpool VS Cachedthreadpool: the Lesser of Two Evils
When to Use an Assertion and When to Use an Exception
Jersey 2.X Custom Injection Annotation with Attributes