Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize empty strings with jackson?

Tags:

java

jackson

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": "",
....
like image 242
hellzone Avatar asked May 09 '18 11:05

hellzone


People also ask

How does Jackson serialize null?

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.

How do I ignore null values in JSON Deserializing?

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.

How do I ignore null values in Jackson?

In Jackson, we can use @JsonInclude(JsonInclude. Include. NON_NULL) to ignore the null fields.


1 Answers

@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.

like image 50
cassiomolin Avatar answered Sep 29 '22 15:09

cassiomolin