Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
256 views
in Technique[技术] by (71.8m points)

java - How to annotate enum fields for deserialization using Jackson json

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?

Inner class

public enum BooleanField
{
    BOOLEAN_TRUE        { public String value() { return "1";} },
    BOOLEAN_FALSE       { public String value() { return "0";} },

Java Bean/Request object

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

The Jackson docs state that it can do this via @JsonValue/@JsonCreator but provides no examples.

Anyone willing to spill the (java)beans, as it were?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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; }

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.

For @JsonCreator, having a static factory method would do it; so adding something like:

@JsonCreator
public static BooleanField forValue(String v) { ... }

Jackson 2.0 will actually support use of just @JsonValue for both, including deserialization.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...