[英]ObjectMapper and Class.forName()
I'm trying to use Jackson's ObjectMapper combined with Class.forName
method. 我试图结合使用
Class.forName
方法结合使用Jackson的ObjectMapper。
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);
}
}
It's not working and I'm getting the following error message: 它无法正常工作,并且出现以下错误消息:
Attempt to invoke virtual method 'java.lang.Class java.lang.Object.getClass()' on a null object reference
However, there are no null references because clazz
variable isn't so. 但是,没有空引用,因为
clazz
变量不是。 What could be the error cause? 错误原因可能是什么?
The problem was I wrote rootName as literal String, not as variable name. 问题是我将rootName写为文字字符串,而不是变量名。
return mapper.treeToValue(root.get("rootName"), clazz); // wrong
return mapper.treeToValue(root.get(rootName), clazz); // correct
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.