我正在尝试使用Jackson的ObjectMapper与Class.forName
方法相结合。
private Object createObject(String json, String rootName) {
try {
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
false);
JsonNode root = mapper.readTree(json);
Class clazz = Class.forName("com.model." + Finder.findClassName(rootName));
return mapper.treeToValue(root.get("rootName"), clazz);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
它不工作,我得到以下错误信息:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
但是,没有空引用,因为clazz
变量不是空的。错误的原因可能是什么?
问题是我写rootName作为文字字符串,而不是变量名。
return mapper.treeToValue(root.get("rootName"), clazz); // wrong
return mapper.treeToValue(root.get(rootName), clazz); // correct