本文介绍了如何使用Jackson json注释enum字段以进行反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Jackson 1.6.2
REST网络服务/ Apache Wink

Jackson 1.6.2REST web service/Apache Wink

如何对枚举字段进行注释以便Jackson对其进行反序列化?

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 / Request对象



Java Bean/Request object

BooleanField locked;
public BooleanField getLocked() {return locked;}

杰克逊文档声明它可以通过 @JsonValue / @JsonCreator 执行此操作,但不提供任何示例(如何帮助!)。我敢肯定他们只是不想让太多人使用他们的框架,所以他们保守秘密。

The Jackson docs state that it can do this via @JsonValue/@JsonCreator but provides no examples (how helpful!). I'm sure they just don't want too many people using their framework so they are keeping this secret.

任何愿意溢出(java)bean的人都是这样吗?

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注释enum字段以进行反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 13:39