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

Lấy giá trị các kiểu dữ liệu từ JSONObject (org.json)

Các phương thức getter chính

JSONObject cung cấp các phương thức để trích xuất giá trị theo kiểu dữ liệu:

  • getString(String key) – trả về String
  • getInt(String key) – trả về int
  • getDouble(String key) – trả về double
  • getBoolean(String key) – trả về boolean
  • getLong(String key), getJSONArray(String key), getJSONObject(String key)…

Tất cả ném JSONException nếu key không tồn tại hoặc kiểu không khớp.

Ví dụ

import org.json.*;

public class JsonGetValuesExample {
    public static void main(String[] args) throws JSONException {
        JSONObject jsonObj = new JSONObject(
            "{" +
            "Name : Adithya," +
            "Age : 22, " +
            "Salary: 10000.00, " +
            "IsSelfEmployee: false " +
            "}"
        );

        System.out.println(jsonObj.getString("Name"));        // Adithya
        System.out.println(jsonObj.getInt("Age"));            // 22
        System.out.println(jsonObj.getDouble("Salary"));      // 10000.0
        System.out.println(jsonObj.getBoolean("IsSelfEmployee")); // false
    }
}

Kết quả

Adithya
22
10000.0
false

Mẹo: Dùng optString(key, defaultValue) để tránh exception và cung cấp giá trị mặc định.