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