I want to deserialize a json with Jackson and I want to map empty strings to STANDARD enum type.
When I try to use JsonProperty with empty string, It ignores empty value and throws exception;
value not one of declared Enum instance names:......,STANDARD,...
Is there any way to handle this?
public enum Type{
@JsonProperty("")
STANDARD,
@JsonProperty("complex")
COMPLEX,
....
}
My json;
....
"type": "",
....
Serialize Null Fields Fields/PropertiesWith its default settings, Jackson serializes null-valued public fields. In other words, resulting JSON will include null fields. Here, the name field which is null is in the resulting JSON string.
You can ignore null fields at the class level by using @JsonInclude(Include. NON_NULL) to only include non-null fields, thus excluding any attribute whose value is null. You can also use the same annotation at the field level to instruct Jackson to ignore that field while converting Java object to json if it's null.
In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.
@JsonValue
will do the trick:
public enum Type {
STANDARD(""),
COMPLEX("complex");
private String value;
StatusType(String value) {
this.value = value;
}
@JsonValue
public String getValue() {
return value;
}
}
Quoting the relevant parts from the @JsonValue
documentation:
Marker annotation that indicates that the value of annotated accessor (either field or "getter" method [a method with non-void return type, no args]) is to be used as the single value to serialize for the instance, instead of the usual method of collecting properties of value. [...]
At most one accessor of a
Class
can be annotated with this annotation; if more than one is found, an exception may be thrown. [...]NOTE: when use for Java enums, one additional feature is that value returned by annotated method is also considered to be the value to deserialize from, not just JSON String to serialize as. This is possible since set of Enum values is constant and it is possible to define mapping, but can not be done in general for POJO types; as such, this is not used for POJO deserialization.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With