There is often a requirement that enumeration constants are used in entity classes, but are serialized into json strings. The default is not the value I want, but the name, as follows
Class
@Data public class TestBean { private TestConst testConst; }
enumeration
@AllArgsConstructor public enum TestConst { AFFIRM_STOCK(12), CONFIRM_ORDER(13),; @Setter @Getter private int status; }
Default result: {"testfirst": "confirm" order "}
Expected result: {"testfirst": 13}
Three methods:
1. Using jackson, this is the simplest
2. If FastJson is used, enumeration class inherits JSONSerializable
3. This method specifies the demultiplexer in the entity class. (only the third method can address serialization and deserialization at the same time)
jackson method
//Add this annotation to the get method of the enumeration @JsonValue public Integer getStatus() { return status; }
TestBean form = new TestBean(); form.setTestConst(TestConst.CONFIRM_ORDER); ObjectMapper mapper = new ObjectMapper(); String mapJakcson = null; try { mapJakcson = mapper.writeValueAsString(form); } catch (JsonProcessingException e) { e.printStackTrace(); } System.out.println(mapJakcson); //{"testConst":13}
fastjson method 1: enumeration inherits JSONSerializable
@AllArgsConstructor public enum TestConst implements JSONSerializable { AFFIRM_STOCK(12) { @Override public void write(JSONSerializer jsonSerializer, Object o, Type type, int i) throws IOException { jsonSerializer.write(this.getStatus()); } }, CONFIRM_ORDER(13) { @Override public void write(JSONSerializer jsonSerializer, Object o, Type type, int i) throws IOException { jsonSerializer.write(this.getStatus()); } },; @Setter @Getter private int status; }
fastjson method 2: https://www.cnblogs.com/insaneXs/p/9515803.html