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

Cách duyệt (iterate) JSONArray trong Android

Giới thiệu

Bài viết này hướng dẫn cách parse và duyệt qua JSONArray trong Android sử dụng thư viện org.json có sẵn trong SDK.

Các bước thực hiện

Bước 1: Tạo dự án mới

Khởi tạo project Android Studio mới.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvJsonResult"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:textStyle="bold" />

</RelativeLayout>

Bước 3: Code Java parse JSON (src/MainActivity.java)

package app.com.sample;

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    TextView tvJsonResult;

    // Chuỗi JSON mẫu: Object chứa array "Employee"
    String jsonString = "{ \"Employee\" :["
        + "{\"ID\":\"01\",\"Name\":\"Sam\",\"Salary\":\"50000\"},"
        + "{\"ID\":\"02\",\"Name\":\"Shankar\",\"Salary\":\"60000\"}"
        + "]}";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tvJsonResult = findViewById(R.id.tvJsonResult);
        parseAndDisplayJson();
    }

    private void parseAndDisplayJson() {
        StringBuilder result = new StringBuilder();

        try {
            // 1. Parse root JSONObject
            JSONObject rootObject = new JSONObject(jsonString);

            // 2. Lấy JSONArray theo key "Employee"
            JSONArray jsonArray = rootObject.optJSONArray("Employee");

            if (jsonArray != null) {
                // 3. Duyệt qua từng element
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject employee = jsonArray.getJSONObject(i);

                    // Lấy giá trị an toàn với optString/optInt (trả về default nếu null/missing)
                    int id = employee.optInt("ID", -1);
                    String name = employee.optString("Name", "N/A");
                    double salary = employee.optDouble("Salary", 0.0);

                    result.append("Nhân viên ").append(i + 1).append(":\n")
                          .append("  ID: ").append(id).append("\n")
                          .append("  Tên: ").append(name).append("\n")
                          .append("  Lương: ").append(String.format("%,.0f", salary)).append(" VNĐ\n\n");
                }
            }

            tvJsonResult.setText(result.toString());

        } catch (JSONException e) {
            e.printStackTrace();
            tvJsonResult.setText("Lỗi parse JSON: " + e.getMessage());
        }
    }
}

Giải thích các phương thức quan trọng:

  • JSONObject(String): Parse chuỗi JSON thành object
  • optJSONArray(key): Lấy array an toàn, trả về null nếu key không tồn tại
  • getJSONObject(index): Lấy object tại vị trí index (ném exception nếu sai)
  • optString/optInt/optDouble(key, default): Lấy giá trị an toàn, có default value
  • length(): Số phần tử trong array

Bước 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>
</manifest>

Chạy ứng dụng

Chạy app, TextView sẽ hiển thị thông tin 2 nhân viên được parse từ JSON string.

Cách duyệt (iterate) JSONArray trong Android

Mở rộng: JSON phức tạp hơn

// JSON lồng nhau
{
  "company": "TechCorp",
  "departments": [
    {
      "name": "Engineering",
      "employees": [
        {"id": 1, "name": "Alice", "skills": ["Java", "Kotlin"]},
        {"id": 2, "name": "Bob", "skills": ["Python", "Go"]}
      ]
    }
  ]
}

// Parse lồng nhau:
JSONObject company = new JSONObject(json);
JSONArray departments = company.optJSONArray("departments");
for (int i = 0; i < departments.length(); i++) {
    JSONObject dept = departments.getJSONObject(i);
    String deptName = dept.optString("name");
    JSONArray employees = dept.optJSONArray("employees");
    // Duyệt employees...
}

Thư viện hiện đại hơn (Khuyên dùng)

  • Gson (Google): Tự động map JSON ↔ Java Object (POJO)
  • Moshi (Square): Hiện đại, hỗ trợ Kotlin, coroutine
  • Kotlinx.serialization: Official Kotlin serialization

Ví dụ với Gson:

// Model
data class Employee(@SerializedName("ID") val id: String,
                    @SerializedName("Name") val name: String,
                    @SerializedName("Salary") val salary: Double)

data class Response(@SerializedName("Employee") val employees: List<Employee>)

// Parse
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
for (Employee emp : response.employees) { ... }