Java:org.codehaus.jackson:如何从字符串反序列化为Enum?

时间:2017-06-05 17:44:24

标签: jackson

我有POJO

import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonProperty;

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyPojo implements Serializable {
    @JsonProperty("id")
    private int id;
    @JsonProperty("type")
    private MyTypeEnum type;
}

我使用注释从字符串(json)反序列化: org.codehaus.jackson.annotate.JsonProperty 。 它工作正常。

但是Enum呢?我如何以大写形式从字符串反序列化为枚举(例如属性“类型”)?

这是我的枚举:

import org.codehaus.jackson.annotate.JsonProperty;
public enum Type {
@JsonProperty("text")
    TEXT("text"),
    @JsonProperty("external")
    EXTERNAL("external"),
    @JsonProperty("event")
    EVENT("event"),
    @JsonProperty("post")
    POST("post"),
    UNKNOWN("Unknown");

    private String name;

    private Type(String name) {
        this.name = name;
    }

    private static Type[] genderList = Type.values();

    public String getName() {
        return name;
    }
}
`

错误:

getLastPromotion: errorMessage: Can not construct instance of com.myproject.Type from String value 'external': value not one of declared Enum instance names
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.bnmt.main.classEnum.PromotionObjectType from String value 'external': value not one of declared Enum instance names
    at org.codehaus.jackson.map.deser.StdDeserializationContext.weirdStringException(StdDeserializationContext.java:243)
    at org.codehaus.jackson.map.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:80)
    at org.codehaus.jackson.map.deser.std.EnumDeserializer.deserialize(EnumDeserializer.java:23)
    at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
    at org.codehaus.jackson.map.deser.SettableBeanProperty$FieldProperty.deserializeAndSet(SettableBeanProperty.java:579)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
    at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
    at org.codehaus.jackson.map.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:104)
    at org.codehaus.jackson.map.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:18)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)

0 个答案:

没有答案