【发布时间】:2020-07-26 13:49:17
【问题描述】:
我一定是做错了...我试图通过使用 ObjecMapper 反序列化 json 来分配一个原始类型,但我无法让它工作。
json 位于一个名为“jsonTest.json”的文件中,如下所示:
{
"simpleVariable":100
}
然后我有一个读取json的方法,其中包含以下代码:
ObjectMapper objectMapper = new ObjectMapper();
Path path = Paths.get("jsonTest.json");
// read the json into a json node
JsonNode rootNode;
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
// read the json file
rootNode = objectMapper.readTree(reader);
} catch(IOException ie) {
rootNode = null;
ie.printStackTrace();
}
// now attempt to assign the value of the node to an int:
int intVar = objectMapper.readValue(rootNode, int.class);
这就是问题所在。当我尝试编译此代码时,出现以下错误:
ObjectMapper 类型中的方法 readValue(JsonParser, Class) 不适用于参数 (JsonNode, Class)。
所以很明显,我已经为 readValue 提供了一个它不能接受的 JsonParser 对象,但我还能如何反序列化一个原语?
【问题讨论】:
标签: java json objectmapper jackson-databind