How to annotate enum fields for deserialization using Jackson json

前端 未结 6 1045
一个人的身影
一个人的身影 2020-12-02 19:59

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          


        
6条回答
  •  旧巷少年郎
    2020-12-02 20:57

    The following may work if the enumeration is an array or not. (Only for deserialization)

    package com.stack.model;
    
    import java.util.HashMap;
    import java.util.Map;
    
    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonIgnore;
    import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
    import com.fasterxml.jackson.annotation.JsonInclude;
    import com.fasterxml.jackson.annotation.JsonProperty;
    import com.fasterxml.jackson.annotation.JsonPropertyOrder;
    
    import lombok.Data;
    
    @Data
    @JsonInclude(JsonInclude.Include.NON_NULL)
    @JsonIgnoreProperties(ignoreUnknown = true)
    @JsonPropertyOrder({ "success", "my-enums" })
    public class MyObjectJSON {
    
        @JsonProperty("sucess")
        private boolean success;
    
        @JsonProperty("my-enums")
        private MyEnum[] myEnums;
    
    
        static enum MyEnum {
            Enum1, Enum2, Enum3, Enum4, EnumN;
    
            private static Map myEnumsMap = new HashMap(5);
    
            static {
                myEnumsMap.put("enum1-val", Enum1);
                myEnumsMap.put("enum2-val", Enum2);
                myEnumsMap.put("enum3-val", Enum3);
                myEnumsMap.put("enum4-val", Enum4);
                myEnumsMap.put("enumn-val", EnumN);
            }
    
            @JsonCreator
            public static MyEnum forValue(String value) {
                return myEnumsMap.get(value.toLowerCase());
            }
        }
    }
    

    To consider:

    1. The @Data annotation generates setters, getters, toString, etc.
    2. @JsonProperty("my-enums") private MyEnum[] myEnums, this is the way to annotate with jackson the field that is of type Enum ( It works if it is an array or not).

    3. MyEnum is the enumeration of the values ​​to be mapped of the JSON object, suppose the following object:

      { "sucess": true, "my-enums": ["enum1-val", "enum3-val"] }

    4. The forValue function allows mapping the string values ​​of the array to Enum, it is annotated with @JsonCreator to indicate a construction factory used in deserialization.

提交回复
热议问题