Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deserialization null value to enum with Jackson

I have problem with JSON deserialization and mapping it to enum. I'm getting JSON from external API simillar to this two examples:

{
 "someValue": null
}
{
 "someValue": "exists"
}

I would like to map null values to some default enum value.

Model object

SomeEnum someValue;

and enum class

public enum SomeEnum {
    @JsonProperty("exists") EXISTS,
    NONE;
}

For exists, value model class contains correct enum, but if I get null from API, it is still null in the model.

I tried to create some method annotated by @JsonCreator, creating own enum deserializer, using @JsonEnumDefaultValue but none of these solutions work for me. Do anyone knows, how can I deserialize nulls to some default enum?

like image 271
Kacper Fleszar Avatar asked Aug 22 '26 04:08

Kacper Fleszar


1 Answers

Ok, so for now I solved this issue by creating custom enum deserializer.

class SomeEnumDeserializer extends StdDeserializer<SomeEnum> {
    SomeEnumDeserializer() {
        super(SomeEnum.class);
    }

    @Override
    public SomeEnum getNullValue(DeserializationContext ctxt) {
        return SomeEnum.NONE;
    }

    @Override
    public SomeEnum deserialize(JsonParser p, DeserializationContext ctxt) {
        // implementation here
    }

and registering it using @JsonDeserialize:

@JsonDeserialize(using = SomeEnumDeserializer.class)
public enum SomeEnum {
// code
}

But still I'd prefer using something like @JsonProperty but for null, like @JsonNullProperty or something like this.

like image 163
Kacper Fleszar Avatar answered Aug 24 '26 17:08

Kacper Fleszar