com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `xxx` from String "PENDING": not one of the values accepted for Enum class: [INIT, DEFAULT, SUCCESS, CANCEL, FAIL]
原创 share_i 发表于:2022-04-09 13:05:34
  阅读 :127   收藏   编辑

枚举类中不含有PENDING,反序列化失败。

解决办法

新增一个对xxx枚举类反序列化的类,需要实现接口JsonDeserializer

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
public class EnumXXXDeserialize extends JsonDeserializer<OrderType> {
  @Override
  public OrderType deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
    JsonNode node = jsonParser.getCodec().readTree(jsonParser);
    try {
      return OrderType.valueOf(node.textValue());
    } catch (Exception e) {
      // maybe null
      log.warn("enum deserializer not found: {}, message: {}",  node.textValue(), e.getMessage());
    }
    return null;
  }
}

枚举类新增注解

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;

@JsonDeserialize(using = EnumXXXDeserialize.class)
public enum OrderType {
  DEFAULT,
  INIT,
  PENDING,
  SUCCESS,
  FAIL,
  CANCEL
}