gpt4 book ai didi

Java - Jackson JSON 库和 ObjectMapper.readValue

转载 作者:行者123 更新时间:2023-11-29 03:07:43 25 4
gpt4 key购买 nike

我有以下 json 数据 (patients.json):

{ 
"A" : {
"name" : "Tom",
"age" : 12
},
"B" : {
"name" : "Jim",
"age" : 54
}
}

使用 Jackson JSON 库,我怎样才能得到如下内容:

HashMap<String, ???> patients = objectMapper.readValue(new File("patients.json"), ???);

String Aname = patients.get("A").get("name");
int Aname = patients.get("A").get("age");

最佳答案

将您的 JSON 反序列化为 Jackson 的 JSON 对象类型,ObjectNode .然后,您可以根据需要遍历它。

例如

ObjectNode patients = objectMapper.readValue(new File("test.json"), ObjectNode.class);
// you can check if it is actually an ObjectNode with JsonNode#isObject()
ObjectNode nodeA = (ObjectNode)patients.get("A");

String name = nodeA.get("name").asText();
int age = (int) nodeA.get("age").asLong();

请注意,如果目标节点无法转换为该类型,方法 asXyz() 将返回默认值。您可以在调用它们之前检查相应的 isXyz() 方法。

关于Java - Jackson JSON 库和 ObjectMapper.readValue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235173/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com