首页 > 文章列表 > 如何在Java中访问JsonNode的JSON字段、数组和嵌套对象?

如何在Java中访问JsonNode的JSON字段、数组和嵌套对象?

java 访问 JsonNode
408 2023-09-02

一个JsonNode是Jackson的JSON树模型,它可以将JSON读取为JsonNode实例,并将JsonNode写入JSON。通过创建ObjectMapper实例并调用readValue()方法,我们可以使用Jackson将JSON读取为JsonNode。我们可以使用JsonNode类的get()方法访问字段、数组嵌套对象。我们可以使用asText()方法返回有效的字符串表示,并使用JsonNode类的asInt()方法将节点的值转换为Java int。

在下面的示例中,我们可以访问JsonNode的JSON字段、数组和嵌套对象。

示例

import com.fasterxml.jackson.databind.*;
import java.io.*;
public class ParseJSONNodeTest {
   public static void main(String args[]) {
      String jsonStr = "{ "name" : "Raja", "age" : 30," +
                       " "technologies" : ["Java", "Scala", "Python"]," +
                       " "nestedObject" : { "field" : "value" } }";
      ObjectMapper objectMapper = new ObjectMapper();
      try {
         JsonNode node = objectMapper.readValue(jsonStr, JsonNode.class);
         JsonNode nameNode = node.get("name");
         String name = nameNode.asText();
         System.out.println(name);
         JsonNode ageNode = node.get("age");
         int age = ageNode.asInt();
         System.out.println(age);
         JsonNode array = node.get("technologies");
         JsonNode jsonNode = array.get(1);
         String techStr = jsonNode.asText();
         System.out.println(techStr);
         JsonNode child = node.get("nestedObject");
         JsonNode childField = child.get("field");
         String field = childField.asText();
         System.out.println(field);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

输出

Raja
30
Scala
value