溫馨提示×

如何使用Java JsonNode處理復(fù)雜JSON

小樊
120
2024-06-19 19:49:13
欄目: 編程語言

在Java中,可以使用Jackson庫中的JsonNode類來處理復(fù)雜的JSON數(shù)據(jù)。以下是一個簡單的示例,演示如何使用JsonNode處理復(fù)雜JSON數(shù)據(jù):

假設(shè)有以下JSON數(shù)據(jù):

{
  "name": "John",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "New York"
  },
  "children": [
    {
      "name": "Alice",
      "age": 5
    },
    {
      "name": "Bob",
      "age": 8
    }
  ]
}

可以使用JsonNode來讀取和操作這個JSON數(shù)據(jù):

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Main {
    public static void main(String[] args) {
        String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\"},\"children\":[{\"name\":\"Alice\",\"age\":5},{\"name\":\"Bob\",\"age\":8}]}";

        try {
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode rootNode = objectMapper.readTree(json);

            String name = rootNode.get("name").asText();
            int age = rootNode.get("age").asInt();
            String street = rootNode.get("address").get("street").asText();
            String city = rootNode.get("address").get("city").asText();

            System.out.println("Name: " + name);
            System.out.println("Age: " + age);
            System.out.println("Street: " + street);
            System.out.println("City: " + city);

            JsonNode children = rootNode.get("children");
            for (JsonNode child : children) {
                String childName = child.get("name").asText();
                int childAge = child.get("age").asInt();
                System.out.println("Child name: " + childName);
                System.out.println("Child age: " + childAge);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

上面的示例代碼演示了如何使用JsonNode類來讀取復(fù)雜的JSON數(shù)據(jù)。首先,我們使用ObjectMapper類將JSON字符串轉(zhuǎn)換為JsonNode對象。然后,我們可以使用get()方法和asXxx()方法來獲取JSON對象的屬性值,并進(jìn)行相應(yīng)的處理。

通過以上方法,可以很容易地處理復(fù)雜的JSON數(shù)據(jù),提取所需的信息并進(jìn)行進(jìn)一步的處理。

0