常常有这么一个需求,实体类里面用到枚举常量,但序列化成json字符串时。默认并非我想要的值,而是名称,以下html
类 java
@Data public class TestBean { private TestConst testConst; }
枚举json
@AllArgsConstructor public enum TestConst { AFFIRM_STOCK(12), CONFIRM_ORDER(13),; @Setter @Getter private int status; }
默认结果:{"testConst":"CONFIRM_ORDER"}app
指望结果:{"testConst":13}ide
3种方法:this
1.使用jackson,这种最简单了code
2.若使用FastJson,枚举类继承JSONSerializableorm
3.这种方法在实体类指定指定编解ma器。(只有第三种方法同时支持序列化和反序列化)htm
jackson方法blog
//在枚举的get方法上加上该注解 @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 方法1:枚举继承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方法2:https://www.cnblogs.com/insaneXs/p/9515803.html