How to deserialize empty strings with jackson?

hellzone :

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": "",
....
cassiomolin :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=462819&siteId=1