How to annotate enum fields for deserialization using Jackson json

前端 未结 6 1071
一个人的身影
一个人的身影 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:46

    don't annotate them, just configure your ObjectMapper instance:

    private ObjectMapper createObjectMapper() {
        final ObjectMapper mapper = new ObjectMapper();
        // enable toString method of enums to return the value to be mapped
        mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
        mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
        return mapper;
    }
    

    and in your enum override the toString() method:

    public enum SectionType {
    START("start"),
    MORE("more");
    
        // the value which is used for matching
        // the json node value with this enum
        private final String value;
    
        SectionType(final String type) {
            value = type;
        }
    
        @Override
        public String toString() {
            return value;
        }
    }
    

    You don't need any annotations or custom deserializers.

提交回复
热议问题