using of Enum Abstract Serializer

4159 views java
7

  1. Example of Enum Abstract Serializer Simple example of an abstract enum ...(Java)(Spring-Boot) [RESOLVED ] using of Enum Abstract Serializer ----------------------------------------------------------------------------------

 @JsonSerialize(using = CatAbstractSerializer.class)
    public enum CatTest implements Tes{

        TYPE1(1, "Type 1"), TYPE2(2, "Type 2");

        private int id;
        private String nome;

        private CatTest(int id, String nome) {
            // TODO Auto-generated constructor stub

            this.id = id;
            this.nome = nome;


        }
        @JsonValue
        public int getId() {
            return id;
        }
        @JsonSetter
        public void setId(int id) {
            this.id = id;
        }
        @JsonValue
        public String getNome() {
            return nome;
        }
        @JsonSetter
        public void setNome(String nome) {
            this.nome = nome;
        }
        @Override
         @JsonValue
         public String toString() {
                return nome;
         }
         @JsonCreator
            public static CatTest fromValueString(String nome) {
                if(nome == null) {
                    throw new IllegalArgumentException();
                }
                for(CatTest nomeSalvo : values()) {
                    if(nome.equals(nomeSalvo.getNome())) {
                        return nomeSalvo;
                    }
                }
                throw new IllegalArgumentException();
            }


    }


    public interface Tes {

        @JsonValue
        int getId();

        @JsonValue
        String getNome();

        @JsonSetter
        void setId(int id);

        @JsonSetter
        void setNome(String nome);


    }

    public class CatAbstractSerializer<T extends Tes> extends JsonSerializer<T> {

        @Override
        public void serialize(T value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            // TODO Auto-generated method stub

            gen.writeStartObject();
            gen.writeFieldName("id");
            gen.writeNumber(value.getId());
            gen.writeFieldName("name");
            gen.writeString(value.getNome());
            gen.writeEndObject();

        }

    }

answered question

Did you mean to answer your own question? If so, can you clearly pose the problem itself and post the solution as an answer, in a way that's understandable to others?

1 Answer

12

Simple solution for those who have many enums ---------------------------------------------

posted this

Have an answer?

JD

Please login first before posting an answer.

Ads

Categories