Java - 通过文本描述从 api 解析枚举

问题描述 投票:0回答:1

我有一个无法更改的库。 这个lib有api方法,它返回像这样的json

{OrderStatus=PartiallyFilledCanceled}
而且这个库还有一个枚举

@AllArgsConstructor
public enum OrderStatus {
    PARTIALLY_FILLED_CANCELED("PartiallyFilledCanceled");
    private final String description;
}

以及带有 OrderStatus 字段的 dto。

所以我得到了一个错误

java.lang.RuntimeException: com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `com.api.client.domain.OrderStatus` from String "PartiallyFilledCanceled": not one of the values accepted for Enum class:[PARTIALLY_FILLED_CANCELED]

我的 ObjectMapper 配置:

objectMapper.registerModule(new JavaTimeModule());
objectMapper.enable(JsonParser.Feature.IGNORE_UNDEFINED);
objectMapper.coercionConfigFor(LogicalType.Enum).setCoercion(CoercionInputShape.EmptyString, CoercionAction.AsNull);

如何在不更改 dto 的情况下使用一些自定义解串器?

java enums deserialization objectmapper
1个回答
0
投票

您需要迭代可能的值并选择具有匹配描述的值。

public class OrderStatusDeserializer extends StdDeserializer<OrderStatus> {

  public OrderStatusDeserializer() {
    super(OrderStatus.class);
  }

  @Override
  public OrderStatus deserialize(JsonParser parser, DeserializationContext context) throws IOException {
    JsonNode node = parser.readValueAsTree();
    String value = node.textValue();
    for (OrderStatus orderStatus : OrderStatus.values()) {
      if (orderStatus.getDescription().equals(value)) {
        return orderStatus;
      }
    }
    //description was not found, handle according to needs
    throw new InvalidFormatException(parser, "Description not found", value, _valueClass);
  }
}

直接使用

ObjectMapper
注册解串器:

ObjectMapper mapper = new ObjectMapper();
SimpleModule myModule = new SimpleModule();
myModule.addDeserializer(OrderStatus.class, new OrderStatusDeserializer());
mapper.registerModule(myModule);
© www.soinside.com 2019 - 2024. All rights reserved.