How to Deserialize a Blank JSON String Value to Null for Java.Lang.String

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



Leave a reply



Submit