猿问

Jackson枚举序列化和反序列化器

我正在使用JAVA 1.6和Jackson 1.9.9我有一个枚举


public enum Event {

    FORGOT_PASSWORD("forgot password");


    private final String value;


    private Event(final String description) {

        this.value = description;

    }


    @JsonValue

    final String value() {

        return this.value;

    }

}

我添加了一个@JsonValue,这似乎可以将对象序列化为:


{"event":"forgot password"}

但是当我尝试反序列化时,我得到了


Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.globalrelay.gas.appsjson.authportal.Event from String value 'forgot password': value not one of declared Enum instance names

我在这里想念什么?


米脂
浏览 2155回答 3
3回答

肥皂起泡泡

请注意,自2015年6月提交此内容(杰克逊2.6.2及更高版本)起,您现在可以简单地编写:public enum Event {    @JsonProperty("forgot password")    FORGOT_PASSWORD;}

阿晨1998

实际答案:枚举的默认反序列化器用于.name()反序列化,因此不使用@JsonValue。因此,正如@OldCurmudgeon指出的那样,您需要传递{"event": "FORGOT_PASSWORD"}以匹配该.name()值。另一个选项(假设您希望写入和读取json值相同)...更多信息:(还有)另一种使用Jackson来管理序列化和反序列化过程的方法。您可以指定以下批注以使用自己的自定义序列化器和反序列化器:@JsonSerialize(using = MySerializer.class)@JsonDeserialize(using = MyDeserializer.class)public final class MyClass {&nbsp; &nbsp; ...}然后,你必须编写MySerializer和MyDeserializer它看起来像这样:MySerializerpublic final class MySerializer extends JsonSerializer<MyClass>{&nbsp; &nbsp; @Override&nbsp; &nbsp; public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // here you'd write data to the stream with gen.write...() methods&nbsp; &nbsp; }}MyDeserializerpublic final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>{&nbsp; &nbsp; @Override&nbsp; &nbsp; public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; // then you'd do something like parser.getInt() or whatever to pull data off the parser&nbsp; &nbsp; &nbsp; &nbsp; return null;&nbsp; &nbsp; }}最后一点,特别是对于对JsonEnum使用该方法进行序列化的枚举执行此操作时getYourValue(),您的序列化器和反序列化器可能如下所示:public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException{&nbsp; &nbsp; gen.writeString(enumValue.getYourValue());}public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException{&nbsp; &nbsp; final String jsonValue = parser.getText();&nbsp; &nbsp; for (final JsonEnum enumValue : JsonEnum.values())&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if (enumValue.getYourValue().equals(jsonValue))&nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return enumValue;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return null;}
随时随地看视频慕课网APP

相关分类

Java
我要回答