用Jackson反序列化泛型枚举时出现问题

hfsqlsce  于 7个月前  发布在  其他
关注(0)|答案(1)|浏览(156)

我有一个这样的类结构:

public class Lame<E extends Enum<E>> {
        private Enum<E> abstractType;
        
        public Enum<E> getAbstractType() {
            return abstractType;
        }
        
        @JsonCreator
        public Lame(E type) {
            this.abstractType = type;
        }
    }
    
    public class InheritLame extends Lame<InheritLame.CounterType> {
        public enum CounterType {
            ONE,
            TWO,
            THREE;
        }
        
        public String name;
        
        @JsonCreator
        public InheritLame(CounterType type) {
            super(type);
            this.name = "NAME";
        }
        
        public String getName() {
            return this.name;
        }
    }

当我示例化一个新的InheritLame对象时,传入一个具体的CounterType值:
InheritLame il = new InheritLame(InheritLame.CounterType.ONE);
我的json输出如下:
{"abstractType":"ONE","name":"NAME"}
然而,当我从JSON字符串重新创建InheritLame对象时,我收到以下错误:

com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `InheritLame$CounterType` from String "abstractType": not one of the values accepted for Enum class: \[TWO, ONE, THREE\]
at \[Source: (String)"{"abstractType":"ONE","name":"NAME"}"; line: 1, column: 2\]
at com.fasterxml.jackson.databind.exc.InvalidFormatException.from(InvalidFormatException.java:67)...

当然,我的真实的对象模型要复杂得多--我们可能有50个不同的枚举类型Map到private Enum<T> abstractType,因此在基类上创建层次结构有点笨拙。
我已经尝试了各种注解,但似乎不能让它工作。似乎很简单,对吧?我对Jackson还很陌生,所以如果答案很明显,请原谅我。谢谢你能提供的任何帮助。

a11xaf1n

a11xaf1n1#

您需要在构造函数中注解type,以便Jackson知道如何Map它:

@JsonCreator
public InheritLame(@JsonProperty("abstractType") CounterType type) {

相关问题