比如有一个 JSON Object :
{"name":"John", "grade":"A"}
或
{"name":"Mike"}
我试着把上面的 JSON 映射为下方的 java 对象。
@JsonIgnoreProperties(ignoreUnknown = true)
public class Employee{
@JsonIgnoreProperties(ignoreUnknown = true)
public enum Grade{ A, B, C }
Grade grade;
String name;
public Grade getGrade() {
return grade;
}
public void setGrade(Grade grade) {
this.grade = grade;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
但是由于 grade 可能不传,所以我希望不传的话,映射对象中 grade 的值就是 null。但是上述办法中,不传的话会报错:
org.codehaus.jackson.map.JsonMappingException: value not one of declared Enum instance names
那么就需要一个办法忽视掉传入的不在 enum types 范围内的值。
解决办法是:
public static void main(String[] args) throws JsonParseException, JsonMappingException, UnsupportedEncodingException, IOException {
String json = "{\"name\":\"John\", \"grade\":\"D\"}";
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL, true);
Employee employee = mapper.readValue(new ByteArrayInputStream(json.getBytes("UTF-8")), Employee.class);
System.out.println(employee.getGrade());
}
This outputs :
null
上面代码的关键在于:在 ObjectMapper 上加上解序列化时的 READ_UNKNOWN_ENUM_VALUES_AS_NULL 配置,就OK了。