REST API 接口要求 requster json 的 lifeCycle 域只能填 YOUNG, OLD,对于其他的 lifeCycle,都要给 requester 返回 bad request 消息。
public class DataCategory {
LifeCycle lifeCycle;
public void setLifeCycle(LifeCycle lifeCycle) {
this.lifeCycle = lifeCycle;
}
public LifeCycle getLifeCycle() {
return lifeCycle;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
String name;
public static void main(String args[]) {
DataCategory dc = new DataCategory();
dc.setName("name");
dc.setLifeCycle(LifeCycle.END_OF_SERVICE);
ObjectMapper objectMapper = new ObjectMapper();
System.out.println(dc.toString());
String jsonStr1 = "{"lifeCycle":"END_OF_SERVICE","name":"false"}";
try {
DataCategory newDC = objectMapper.readValue(jsonStr1, DataCategory.class);
System.out.println(newDC.getLifeCycle());
System.out.println(String.valueOf(newDC.getLifeCycle()));
} catch (IOException e) {
e.printStackTrace();
}
try {
System.out.println(objectMapper.writeValueAsString(dc));
} catch (Exception e) {
e.printStackTrace();
}
}
}
jackson可以正常的进行序列化和反序列化。
但是插入到 mongodb 中时就报错,说序列化 class 失败。而getLifeCycle().toString()又不work。
因此使用 String.valueOf(getLifeCycle()) 来从 枚举类型转化到 String