【问题标题】:Java - Jackson JSON Library and ObjectMapper.readValueJava - Jackson JSON 库和 ObjectMapper.readValue
【发布时间】:2015-07-05 21:29:16
【问题描述】:

我有以下 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");

【问题讨论】:

    标签: java json jackson


    【解决方案1】:

    将您的 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() 方法。

    【讨论】:

      【解决方案2】:

      您可以创建一个类来将您的患者映射到;

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

      然后通过 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();
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 2012-07-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多