Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Truy cập field, array và nested object của JsonNode trong Java (Jackson)

JsonNode là tree model của Jackson cho JSON. Có thể đọc JSON vào JsonNode instance bằng cách tạo ObjectMapper instance và gọi readValue(). Truy cập field, array hoặc nested object dùng phương thức get() của JsonNode. Trả về string representation dùng asText(), chuyển giá trị node sang Java int dùng asInt().

Ví dụ minh họa

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);
            
            // Truy cập field đơn giản
            JsonNode nameNode = node.get("name");
            String name = nameNode.asText();
            System.out.println(name); // Raja
            
            // Truy cập field số
            JsonNode ageNode = node.get("age");
            int age = ageNode.asInt();
            System.out.println(age); // 30
            
            // Truy cập array element
            JsonNode array = node.get("technologies");
            JsonNode jsonNode = array.get(1); // index 1
            String techStr = jsonNode.asText();
            System.out.println(techStr); // Scala
            
            // Truy cập nested object
            JsonNode child = node.get("nestedObject");
            JsonNode childField = child.get("field");
            String field = childField.asText();
            System.out.println(field); // value
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Kết quả đầu ra

Raja
30
Scala
value

Mẹo: Dùng node.path("field") thay get() để trả về MissingNode (không null) nếu field không tồn tại, tránh NullPointerException. asText(), asInt(), asLong(), asBoolean(), asDouble() chuyển kiểu an toàn.