[英]Java - Jackson JSON Library and ObjectMapper.readValue
我有以下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()
方法进行检查。
您可以创建一个类来将您的患者映射到;
private static class Patient {
@JsonProperty("name")
private String name;
@JsonProperty("age")
private int age;
public Patient() { }
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
然后通过杰克逊将您的json读入其中
HashMap<String, Patient> patients = objectMapper.readValue(new File("patients.json"), new TypeReference<HashMap<String,Patient>>() {});
Patient patientA = patients.get("A");
String patientAName = patientA.getName();
int pateintAAge = patientA.getAge();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.