无法使用START_OBJECT令牌反序列化MyEnum实例

时间:2019-05-16 20:14:38

标签: jackson spring-webflux

困扰着MyEnum枚举从JSON反序列化到POJO的问题,无法弄清楚我做错了什么。因此,基本上我尝试检索一些调用特定微服务端点的数据,这些数据返回以下json:

    {
      "id": "9cabf3e9-965d-4407-b62b-c57dd6006419",
      "myEnums": [
        {
          "context": "SOME_FOO_CONTEXT_1",
          "feature": "SOME_BAR_FEATURE_1",
          "name": "SOME_FOO_BAR_1"
        },
        {
          "context": "SOME_FOO_CONTEXT_2",
          "feature": "SOME_BAR_FEATURE_2",
          "name": "SOME_FOO_BAR_2"
        }
      ],
      "name": "Some name",
      "updatedBy": null,
      "updated": "2019-05-16T00:11:19.279Z"
    }

这是一种方法,它调用另一个微服务端点,将响应主体反序列化为POJO,然后将结果返回为Set:

      private Mono<Set<MyEnum>> fetchMyEnums(UUID someId) {
            return webClient.get().uri("/v1/something/{id}", someId)
                            .retrieve()
                            .bodyToMono(MyClass.class)
                            .flatMapIterable(MyClass::getMyEnums)
                            .collect(toSet());
        }

用于JSON反序列化的类:

    @lombok.Value
    static class MyClass {

        List<MyEnum> myEnums;

    }

我实际上无法反序列化的枚举:

    @Getter
    @RequiredArgsConstructor
    @AllArgsConstructor
    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public enum MyEnum {

        SOME_FOO_BAR_1(SOME_FOO_CONTEXT_1, SOME_BAR_FEATURE_1),
        SOME_FOO_BAR_2(SOME_FOO_CONTEXT_2, SOME_BAR_FEATURE_2);

        private final FooEnum context;
        private final BarEnum feature;
        private       String  name;

        @JsonProperty
        public String getName() {
            return super.name();
        }

    }

反序列化期间,我收到以下异常:

    org.springframework.core.codec.DecodingException: JSON decoding error: Cannot deserialize instance of `com.learn.common.security.model.MyEnum` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.learn.common.security.model.MyEnum` out of START_OBJECT token
     at [Source: UNKNOWN; line: -1, column: -1] (through reference chain: com.learn.common.security.service.MyEnumService$MyClass["myEnums"]->java.util.ArrayList[0])

我在哪里弄错了?

1 个答案:

答案 0 :(得分:0)

因此花一些时间来澄清反序列化的问题,我发现对于其Shape.Object的Enum没有自动反序列化。

但是我找到了一种解决方法,如何从json反序列化MyEnum对象(您需要定义将其标记为JsonCreator的静态方法,并定义期望从使用fieldName定义JsonProperty的对象中捕获的输入参数):

@Getter
@RequiredArgsConstructor
@AllArgsConstructor
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum {

    SOME_FOO_BAR_1(SOME_FOO_CONTEXT_1, SOME_BAR_FEATURE_1),
    SOME_FOO_BAR_2(SOME_FOO_CONTEXT_2, SOME_BAR_FEATURE_2);

    private final FooEnum context;
    private final BarEnum feature;
    private       String  name;

    @JsonProperty
    public String getName() {
        return super.name();
    }

    @JsonCreator
    public static Permission fromJson(@JsonProperty("name") String name) {
        return valueOf(name);
    }

}