如何使用 Jackson json 注释枚举字段以进行反序列化 [英] How to annotate enum fields for deserialization using Jackson json
问题描述
我在 Jackson 1.6.2 中使用 REST web 服务/Apache Wink.如何注释枚举字段以便 Jackson 反序列化它?
I am using REST web service/Apache Wink with Jackson 1.6.2. How do I annotate an enum field so that Jackson deserializes it?
public enum BooleanField
{
BOOLEAN_TRUE { public String value() { return "1";} },
BOOLEAN_FALSE { public String value() { return "0";} },
Java Bean/请求对象
BooleanField locked;
public BooleanField getLocked() {return locked;}
Jackson 文档声明它可以通过 @JsonValue
/@JsonCreator
做到这一点,但没有提供示例.
The Jackson docs state that it can do this via @JsonValue
/@JsonCreator
but provides no examples.
有人愿意把 (java)beans 洒出来吗?
Anyone willing to spill the (java)beans, as it were?
推荐答案
如果您使用的是 Jackson 1.9,序列化将通过以下方式完成:
If you are using Jackson 1.9, serialization would be done by:
public enum BooleanField {
BOOLEAN_TRUE("1")
;
// either add @JsonValue here (if you don't need getter)
private final String value;
private BooleanField(String value) { this.value = value; }
// or here
@JsonValue public String value() { return value; }
所以你需要的改变是向 Enum 类型本身添加方法,所以所有的值都有它.不确定它是否适用于子类型.
so change you need is to add method to Enum type itself, so all values have it. Not sure if it would work on subtype.
对于@JsonCreator
,有一个静态工厂方法就可以了;所以添加如下内容:
For @JsonCreator
, having a static factory method would do it; so adding something like:
@JsonCreator
public static BooleanField forValue(String v) { ... }
Jackson 2.0 实际上将支持对两者仅使用 @JsonValue
,包括反序列化.
Jackson 2.0 will actually support use of just @JsonValue
for both, including deserialization.
这篇关于如何使用 Jackson json 注释枚举字段以进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!