简体   繁体   English

Java-Jackson JSON库和ObjectMapper.readValue

[英]Java - Jackson JSON Library and ObjectMapper.readValue

I have the following json data (patients.json): 我有以下json数据(patients.json):

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

Using the Jackson JSON library, how can I get something like the following: 使用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");

Deserialize your JSON into Jackson's JSON Object type, ObjectNode . 将您的JSON反序列化为Jackson的JSON对象类型ObjectNode You can then traverse it as you see fit. 然后,您可以根据需要遍历它。

For example 例如

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();

Note that the methods asXyz() return default values if the target node cannot be converted to that type. 请注意,如果无法将目标节点转换为该类型,则方法asXyz()返回默认值。 You can check with the corresponding isXyz() methods before invoking them. 您可以在调用它们之前使用相应的isXyz()方法进行检查。

You could create a class to map your patients to; 您可以创建一个类来将您的患者映射到;

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;
    }
}

Then read your json into it via jackson 然后通过杰克逊将您的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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM