常常有這麼一個需求,實體類裏面用到枚舉常量,但序列化成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