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

วิธีวนลูปอ่าน JSON Array ใน Android

ภาพรวม

ตัวอย่างนี้แสดงวิธีการ Parse และวนลูปอ่านข้อมูลจาก JSON Array โดยใช้คลาส org.json ที่มาพร้อม Android SDK

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่

เปิด Android Studio ไปที่ File → New Project แล้วกรอกข้อมูลที่จำเป็น

ขั้นตอนที่ 2: จัดรูปแบบหน้าจอ (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/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textSize="16sp"
        android:textStyle="bold" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ดหลัก (MainActivity.java)

package com.example.jsonarraydemo;

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 textView;
    
    // JSON String ตัวอย่าง
    String strJson = "{ \"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);
        
        textView = findViewById(R.id.textView);
        parseJsonArray();
    }

    private void parseJsonArray() {
        StringBuilder data = new StringBuilder();
        
        try {
            JSONObject jsonRootObject = new JSONObject(strJson);
            JSONArray jsonArray = jsonRootObject.optJSONArray("Employee");
            
            if (jsonArray != null) {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    
                    int id = jsonObject.optInt("ID");
                    String name = jsonObject.optString("Name");
                    double salary = jsonObject.optDouble("Salary");
                    
                    data.append("Employee ").append(i).append(":\n")
                        .append("ID: ").append(id).append("\n")
                        .append("Name: ").append(name).append("\n")
                        .append("Salary: ").append(salary).append("\n\n");
                }
                textView.setText(data.toString());
            }
        } catch (JSONException e) {
            e.printStackTrace();
            textView.setText("JSON Parsing Error: " + e.getMessage());
        }
    }
}

ขั้นตอนที่ 4: ตั้งค่า Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.jsonarraydemo">
    <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>

การทดสอบ

รันแอปพลิเคชันบนอุปกรณ์จริง จะแสดงข้อมูลพนักงาน 2 รายการที่ Parse จาก JSON

วิธีวนลูปอ่าน JSON Array ใน Android

เคล็ดลับและ Best Practices

  • ใช้ optJSONArray(), optString(), optInt() แทน get... เพื่อกัน Crash เมื่อ Key ไม่มี
  • สำหรับ JSON ซับซ้อน/ขนาดใหญ่ ควรใช้ Library Gson หรือ Moshi
  • ควรทำ Parsing ใน Background Thread (Coroutine/RxJava) เพื่อไม่บล็อก UI
  • ใช้ jsonObject.has("key") ตรวจสอบ Key ก่อนอ่าน