Serializing enums with Jackson

后端 未结 7 1370
借酒劲吻你
借酒劲吻你 2020-11-28 01:50

I have an Enum desrcibed below:

public enum OrderType {

  UNKNOWN(0, \"Undefined\"),
  TYPEA(1, \"Type A\"),
  TYPEB(2, \"Type B\"),
  TYPEC(3, \"Type C\");         


        
7条回答
  •  时光说笑
    2020-11-28 02:26

    I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6.

    public class CustomObjectMapper extends ObjectMapper {
        @PostConstruct
        public void customConfiguration() {
            // Uses Enum.toString() for serialization of an Enum
            this.enable(WRITE_ENUMS_USING_TO_STRING);
            // Uses Enum.toString() for deserialization of an Enum
            this.enable(READ_ENUMS_USING_TO_STRING);
        }
    }
    

    There are more enum-related features available, see here:

    https://github.com/FasterXML/jackson-databind/wiki/Serialization-features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

提交回复
热议问题