经常有这么一个需求,实体类里面用到枚举常量,但序列化成json字符串时。默认并不是我想要的值,而是名称,如下
类
@Data
public class TestBean {
private TestConst testConst;
}
枚举
@AllArgsConstructor
public enum TestConst {
AFFIRM_STOCK(12),
CONFIRM_ORDER(13),;
@Setter
@Getter
private int status;
}
默认结果:{"testConst":"CONFIRM_ORDER"}
期望结果:{"testConst":13}
3种方法:
1.使用jackson,这种最简单了
2.若使用FastJson,枚举类继承JSONSerializable
3.这种方法在实体类指定指定编解ma器。(只有第三种方法同时支持序列化和反序列化)
jackson方法
//在枚举的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
转载于:https://my.oschina.net/yejunxi/blog/2209485