3 回答

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

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