Serializing enums with Jackson

后端 未结 7 1369
借酒劲吻你
借酒劲吻你 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:25

    Use @JsonCreator annotation, create method getType(), is serialize with toString or object working

    {"ATIVO"}
    

    or

    {"type": "ATIVO", "descricao": "Ativo"}
    

    ...

    import com.fasterxml.jackson.annotation.JsonCreator;
    import com.fasterxml.jackson.annotation.JsonFormat;
    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.node.JsonNodeType;
    
    @JsonFormat(shape = JsonFormat.Shape.OBJECT)
    public enum SituacaoUsuario {
    
        ATIVO("Ativo"),
        PENDENTE_VALIDACAO("Pendente de Validação"),
        INATIVO("Inativo"),
        BLOQUEADO("Bloqueado"),
        /**
         * Usuarios cadastrados pelos clientes que não possuem acesso a aplicacao,
         * caso venham a se cadastrar este status deve ser alterado
         */
        NAO_REGISTRADO("Não Registrado");
    
        private SituacaoUsuario(String descricao) {
            this.descricao = descricao;
        }
    
        private String descricao;
    
        public String getDescricao() {
            return descricao;
        }
    
        // TODO - Adicionar metodos dinamicamente
        public String getType() {
            return this.toString();
        }
    
        public String getPropertieKey() {
            StringBuilder sb = new StringBuilder("enum.");
            sb.append(this.getClass().getName()).append(".");
            sb.append(toString());
            return sb.toString().toLowerCase();
        }
    
        @JsonCreator
        public static SituacaoUsuario fromObject(JsonNode node) {
            String type = null;
            if (node.getNodeType().equals(JsonNodeType.STRING)) {
                type = node.asText();
            } else {
                if (!node.has("type")) {
                    throw new IllegalArgumentException();
                }
                type = node.get("type").asText();
            }
            return valueOf(type);
        }
    
    }
    

提交回复
热议问题