Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

เข้าถึง JSON Fields, Arrays, Nested Objects ของ JsonNode ใน Java (Jackson)

JsonNode เป็น Jackson's Tree Model สำหรับ JSON อ่าน JSON เข้า JsonNode Instance ด้วย ObjectMapper เรียก readValue() เข้าถึง Field, Array, Nested Object ด้วยเมธอด get() ของ JsonNode ใช้ asText() คืน String, asInt() แปลงเป็น Java int

ตัวอย่าง: Access JSON Fields, Arrays, Nested Objects

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);
            
            // Field ธรรมดา
            JsonNode nameNode = node.get("name");
            String name = nameNode.asText();
            System.out.println(name);  // Raja
            
            // Field เป็น Number
            JsonNode ageNode = node.get("age");
            int age = ageNode.asInt();
            System.out.println(age);  // 30
            
            // Array - เข้าถึง Element Index 1
            JsonNode array = node.get("technologies");
            JsonNode jsonNode = array.get(1);
            String techStr = jsonNode.asText();
            System.out.println(techStr);  // Scala
            
            // 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();
        }
    }
}

ผลลัพธ์

Raja
30
Scala
value

JsonNode Methods สำคัญ:

  • get(String fieldName) - ดึง Child Node
  • get(int index) - ดึง Array Element
  • asText(), asInt(), asLong(), asDouble(), asBoolean()
  • isArray(), isObject(), isNull(), has(String fieldName)
  • fields() - Iterator ของ Fields
  • elements() - Iterator ของ Array Elements