JSON Binding @JsonbTypeDeserializer annotation ignored on enums?

时光怂恿深爱的人放手 提交于 2021-01-28 06:36:28

问题


I'm converting a JAXB application to JSON-B and I've run into an issue while trying to deserialize a Java enum using a custom JsonbDeserializer inside one of my tests.

The original JSON I need to deserialize contains ints referencing the enum's constants. Therefore my custom JsonbDeserializer needs to take the int and return the enum constant with the matching ordinal. It looks like this:

@JsonbTypeDeserializer(Region.RegionDeserializer.class)
public enum Region implements BaseEnum {

    REGION_A,
    REGION_B;

    static final class RegionDeserializer implements JsonbDeserializer<Region> {

        // deserialize() method returns REGION_A for 0 and REGION_B for 1.

    }
}

Then I run it like this:

try (var jsonb = JsonbBuilder.create()) {
    var result = jsonb.fromJson(text, Region.class);
} catch (final Exception ex) {
    fail(ex);
}

Unfortunately, here's what I get back:

java.lang.IllegalArgumentException: No enum constant Region.1
    at java.base/java.lang.Enum.valueOf(Enum.java:266)
    at org.eclipse.yasson.internal.serializer.EnumTypeDeserializer.deserialize(EnumTypeDeserializer.java:40)

As you can see, RegionDeserializer is not used. Instead, the default enum deserializer is used. Looking into the JSON-B docs, I see I should register the deserializer manually:

JsonbConfig config = new JsonbConfig()
    .withDeserializer(RegionDeserializer.class);
Jsonb jsonb = JsonbBuilder.create(config);
...

And when I do that, the code in fact works. But here's my question - what can I do to have the JsonbTypeDeserializer annotation registered automatically? Considering I have a lot of enums I need custom deserializers for, registering them manually really doesn't scale.

EDIT 1: I have tried to use @JsonbCreator-annotated static method instead, and the result was the same. The default enum deserializer was still used.


回答1:


The JSON-B specification mentions both ways of registering the custom deserializer:

There are two ways how to register JsonbSerializer/JsonbDeserializer:

  • Using JsonbConfig::withSerializers/JsonbConfig::withDeserializers method;
  • Annotating a type with JsonbSerializer/JsonbDeserializer annotation.

The fact that the annotation does not work is a bug. I could reproduce this on Yasson 1.0.6, but not on Yasson 2.0.0-M1. Perhaps updating to the latest version solves your problem?



来源:https://stackoverflow.com/questions/60572894/json-binding-jsonbtypedeserializer-annotation-ignored-on-enums

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!