Jackson JSON to an empty string
Cause of Jackson JSON to an empty string
This problem of Jackson JSON null to an empty string mainly occurs in Jackson. One example of the above problem is shown in the following code.
public class POI { @JsonProperty("name") private String name; }
In this code sometimes the server returns the “name” as a null value. Our major task is that we can return the same name value but in a form of a string.
Solution
One of the most amazing facts behind this problem’s solution is that there is a new feature in Jackson 2.9. Jackson 2.9 introduces a brand-new technique that hasn’t yet been mentioned: the use of @JsonSetter for properties and “Config Overrides” for types like String.class in place of it.
In short, this new feature of Jackson 2.9 allows you to mark any field or setter value.
public String stringValue;
Additionally, it enables the configuration mapper to carry out the same action for all String value properties. The code for the same is:
mapper.configOverride(String.class)
.setSetterInfo(JsonSetter.Value.forValueNulls(Nulls.AS_EMPTY));
It would both change an incoming null into an empty value, which for Strings is “.
This also functions with collections and maps.
If one wants to solve this problem with an easy solution i.e by using no Jackson specialties. To do this we need to create a getter for a name that returns an empty String rather than null because Jackson serializes with those. The code for the same is:
public String getName() {
return name != null ? name : "";
}
Also Read: what is Attribute error and how to solve it?