实际答:
默认解串器枚举使用.name()
反序列化,所以它不使用@JsonValue
。正如@OldCurmudgeon指出的那样,您需要传入{"event": "FORGOT_PASSWORD"}
以匹配.name()
的值。
的另一种选择(假设你想要写和读的JSON值是相同的)...
更多信息:
有(又)另一种方式来管理序列化和与杰克逊的反序列化过程。您可以指定这些批注使用自己定制的串行器和解串:
@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;
}
}
最后一点,尤其是对这样做是为了与方法getYourValue()
序列化的枚举JsonEnum
,你的串行器和解串可能是这样的:
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;
}
你试过'{“Event”:“FORGOT_PASSWORD”}'?请注意事件和FORGOT_PASSWORD上的大写字母。 – OldCurmudgeon
类似的:[如何使用杰克逊JSON来注释为反序列化枚举字段(https://stackoverflow.com/questions/9300191/how-to-annotate-enum-fields-for-deserialization-using-jackson-json) – Vadzim