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

วิธี Parse JSONArray ในแอป Android

ภาพรวม

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

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 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"
    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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

    private TextView textView;

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

        textView = findViewById(R.id.textView);

        // JSON String ตัวอย่าง (ในโปรดักชันมักมาจาก API Response)
        String jsonString = "{ \"Basic info\": [" +
                "{\"Name\":\"Mash\",\"Age\":\"27\",\"Gender\":\"Male\"}," +
                "{\"Name\":\"Niyaz\",\"Age\":\"23\",\"Gender\":\"Male\"}" +
                "]}";

        StringBuilder result = new StringBuilder();

        try {
            // 1. Parse เป็น JSONObject ราก
            JSONObject jsonRoot = new JSONObject(jsonString);

            // 2. ดึง JSONArray จาก key "Basic info"
            JSONArray jsonArray = jsonRoot.optJSONArray("Basic info");

            if (jsonArray != null) {
                // 3. วนลูปอ่านแต่ละ Object ใน Array
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);

                    // ใช้ optString/optInt ป้องกัน Crash ถ้า Key ไม่มี
                    String name = jsonObject.optString("Name", "N/A");
                    int age = jsonObject.optInt("Age", 0);
                    String gender = jsonObject.optString("Gender", "N/A");

                    result.append("Person ").append(i + 1).append(":\n");
                    result.append("  Name: ").append(name).append("\n");
                    result.append("  Age: ").append(age).append("\n");
                    result.append("  Gender: ").append(gender).append("\n\n");
                }
            }

            textView.setText(result.toString());

        } catch (JSONException e) {
            e.printStackTrace();
            textView.setText("JSON Parse Error: " + e.getMessage());
        }
    }
}

ขั้นตอนที่ 4: AndroidManifest.xml

<?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>
                
                
            </intent-filter>
        </activity>

    </application>
</manifest>

การทดสอบ

รันแอป → จะแสดงข้อมูล 2 คนที่ Parse จาก JSON String

วิธี Parse JSONArray ในแอป Android

เปรียบเทียบ Method: get vs opt

Methodพฤติกรรมเมื่อ Key ไม่มีใช้เมื่อไหร่
getString()โยน JSONExceptionKey ต้องมีแน่นอน (Required field)
optString()คืนค่า default (default = "")Key อาจไม่มี (Optional field)
optString(key, default)คืนค่า default ที่ระบุต้องการค่า default เฉพาะเจาะจง
getInt()โยน JSONExceptionRequired numeric field
optInt()คืนค่า 0
optInt(key, default)คืนค่า default ที่ระบุ

💡 แนะนำ: ใช้ Library ทันสมัย

ในโปรเจกต์จริง แนะนำให้ใช้ Gson, Moshi, หรือ Kotlinx.serialization แทนการ Parse ด้วยมือ:

// Gson Example
implementation 'com.google.code.gson:gson:2.10'

// Data Class
data class Person(
    @SerializedName("Name") val name: String,
    @SerializedName("Age") val age: Int,
    @SerializedName("Gender") val gender: String
)

data class Response(
    @SerializedName("Basic info") val basicInfo: List
)

// Parse ง่ายมาก
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);