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

วิธี Parse JSON ด้วย JSONObject ใน Android Kotlin

บทนำ

ตัวอย่างนี้แสดงวิธีแยกวิเคราะห์ (Parse) ข้อมูล JSON โดยใช้ org.json.JSONObject คลาสมาตรฐานของ Android (ไม่ต้องเพิ่ม Library)

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

สร้างโปรเจกต์ Android ใหม่ใน Android Studio

ขั้นตอนที่ 2: 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"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="JSON Parser Demo"
        android:textAlignment="center"
        android:textColor="@android:color/holo_green_dark"
        android:textSize="32sp"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:textColor="@android:color/background_dark"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

ขั้นตอนที่ 3: MainActivity.kt

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

class MainActivity : AppCompatActivity() {
    // JSON String ตัวอย่าง (ในทางปฏิบัติมาจาก API Response)
    private val jsonString = "{\"employee\":{\"name\":\"Niyaz\",\"salary\":56000,\"department\":\"Engineering\",\"skills\":[\"Kotlin\",\"Java\",\"Python\"]}}"
    
    private lateinit var textView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        title = "JSON Parser"

        textView = findViewById(R.id.textView)
        parseJson()
    }

    private fun parseJson() {
        try {
            val rootObject = JSONObject(jsonString)
            val employee = rootObject.getJSONObject("employee")
            
            val name = employee.getString("name")
            val salary = employee.getInt("salary")
            val department = employee.getString("department")
            val skillsArray = employee.getJSONArray("skills")
            
            val skills = StringBuilder()
            for (i in 0 until skillsArray.length()) {
                skills.append(skillsArray.getString(i))
                if (i < skillsArray.length() - 1) skills.append(", ")
            }

            val result = buildString {
                appendLine("Employee Details:")
                appendLine("Name: $name")
                appendLine("Salary: \$$salary")
                appendLine("Department: $department")
                appendLine("Skills: $skills")
            }
            
            textView.text = result

        } catch (e: JSONException) {
            e.printStackTrace()
            textView.text = "JSON Parsing Error: ${e.message}"
        }
    }
}

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

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

JSONObject Methods ที่ใช้บ่อย

Methodคืนค่าคำอธิบาย
getString(key)Stringดึงค่า String
getInt(key)Intดึงค่า Integer
getLong(key)Longดึงค่า Long
getDouble(key)Doubleดึงค่า Double
getBoolean(key)Booleanดึงค่า Boolean
getJSONObject(key)JSONObjectดึง Object ซ้อน (Nested)
getJSONArray(key)JSONArrayดึง Array
has(key)Booleanตรวจสอบว่ามี Key นี้หรือไม่
isNull(key)Booleanตรวจสอบค่า Null
optString(key, default)Stringดึงค่า พร้อม Default ถ้าไม่มี/Null

JSONArray Methods

val jsonArray = JSONObject(jsonString).getJSONArray("items")
for (i in 0 until jsonArray.length()) {
    val item = jsonArray.getJSONObject(i)
    val name = item.getString("name")
    // ...
}

// หรือแปลงเป็น List
val list = mutableListOf()
for (i in 0 until jsonArray.length()) {
    list.add(jsonArray.getString(i))
}

แนวทางทันสมัย: Kotlinx Serialization / Gson / Moshi

แนะนำให้ใช้ Library แทน JSONObject ดิบ เพราะ:

  • Type-safe - Map ตรงกับ Data Class
  • Less Boilerplate - ไม่ต้อง getString/getInt ทุกฟิลด์
  • Null Safety - จัดการ Nullable ได้ดี
  • Performance - เร็วกว่า (โดยเฉพาะ Moshi/Gson streaming)

ตัวอย่าง Kotlinx Serialization

@Serializable
data class Employee(
    val name: String,
    val salary: Int,
    val department: String,
    val skills: List
)

@Serializable
data class Response(val employee: Employee)

// ใช้งาน
val response = Json.decodeFromString(jsonString)
println(response.employee.name) // Type-safe!

ตัวอย่าง Gson

// build.gradle
implementation 'com.google.code.gson:gson:2.10.1'

// ใช้งาน
val gson = Gson()
val employee = gson.fromJson(jsonString, Employee::class.java)