0

I use @JsonSerialize to convert the enum class to Integer, and the writing is successful; but each enum class must write a converted class, is there a way to write only one conversion class?

I tried to use generics to get the type of the enum class, but failed, this is not allowed

//   error code

@JsonSerialize(using = StatusSerializer<StatusEnum>.class)
private Integer status;
@Data
public class ZkUser   {


    /**
     * name
     */
    private String name;

    /**
     * status
     */
    @JsonSerialize(using = StatusSerializer.class)
    private Integer status;


}

//==========================================================================================
public enum StatusEnum {

   // d
    ON(1),
   
    OFF(0);

    private final Integer code;


    public static StatusEnum getEnumByCode(Integer code) {
        for (StatusEnum s : values()) {
            if (s.code.equals(code)) {
                return s;
            }

        }
        return null;
    }

    StatusEnum(Integer code) {
        this.code = code;
    }
    
    public Integer getCode() {
        return code;
    }
}

//=========================================================================================
public class StatusSerializer<T> extends JsonSerializer<Integer> {

    private T t;


    @Override
    public void serialize(Integer value, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {

            var b = StatusEnum.getEnumByCode(value);
            jsonGenerator.writeObject(b);
    }


}


realheyu
  • 1
  • 1

1 Answers1

0

You can both serialize and deserialize an enum by adding the @JsonValue annotation (see this answer). The following example is based on your enum:

public class Main {

    public static enum StatusEnum {
        ON(1),
        OFF(0);

        private final Integer code;

        StatusEnum(Integer code) {
            this.code = code;
        }

        @JsonValue
        public Integer getCode() {
            return code;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();

        String jsonString = objectMapper.writeValueAsString(StatusEnum.ON);
        System.out.println(jsonString);

        StatusEnum readEnum = objectMapper.readValue(jsonString, StatusEnum.class);
        System.out.println(readEnum);
    }
}

The program outputs:

1
ON
JANO
  • 2,995
  • 2
  • 14
  • 29