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

วิธี Parse JSON String ใน Android

บทนำ

ตัวอย่างนี้แสดงวิธี Parse (แยกวิเคราะห์) JSON String ที่เก็บไว้ในตัวแปร โดยใช้ Class JSONObject และ JSONArray ของ Android SDK (org.json) โดยไม่ต้องใช้ Library ภายนอก

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

Android Studio → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="30sp" />

</LinearLayout>

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

package com.example.myapplication;

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

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

public class MainActivity extends AppCompatActivity {

    TextView textView;

    // JSON String ตัวอย่าง (Hardcoded)
    String json = "{"
        + " \"geodata\": ["
        + " {"
        + " \"id\": \"1\","
        + " \"name\": \"Julie Sherman\","
        + " \"gender\": \"female\","
        + " \"latitude\": \"37.33774833333334\","
        + " \"longitude\": \"-121.88670166666667\""
        + " }"
        + " ]"
        + "}";

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.text);

        try {
            // 1. Parse String เป็น JSONObject
            final JSONObject obj = new JSONObject(json);

            // 2. ดึง JSONArray ชื่อ "geodata"
            final JSONArray geodata = obj.getJSONArray("geodata");

            // 3. ดึง Object แรกใน Array (index 0)
            final JSONObject person = geodata.getJSONObject(0);

            // 4. ดึงค่า String ตาม Key
            textView.setText(person.getString("name"));

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }
}

ผลลัพธ์

วิธี Parse JSON String ใน Android

โครงสร้าง JSON และการ Parse

{
  "geodata": [           ← JSONObject.getJSONArray("geodata")
    {                    ← JSONArray.getJSONObject(0)
      "id": "1",         ← JSONObject.getString("id")
      "name": "Julie Sherman",  ← JSONObject.getString("name")
      "gender": "female",
      "latitude": "37.33774833333334",
      "longitude": "-121.88670166666667"
    }
  ]
}

เมธอดหลักของ JSONObject / JSONArray

เมธอด คืนค่า คำอธิบาย
getString(key)Stringดึงค่าข้อความ (โยน Exception หากไม่มี key)
optString(key, default)Stringดึงค่าข้อความ (คืนค่า default หากไม่มี key - แนะนำ)
getInt(key)intดึงค่าตัวเลขจำนวนเต็ม
getDouble(key)doubleดึงค่าทศนิยม
getBoolean(key)booleanดึงค่า True/False
getJSONObject(key)JSONObjectดึง Nested Object
getJSONArray(key)JSONArrayดึง Nested Array
has(key)booleanตรวจสอบว่ามี Key นี้หรือไม่
length()intจำนวน Element ใน JSONArray

Best Practices

  • ใช้ optXxx() แทน getXxx(): ป้องกัน Crash เมื่อ Key ไม่มีหรือ Null
  • Try-Catch JSONException: ครอบทุกการ Parse
  • Library แนะนำ: Gson, Moshi, Kotlinx Serialization - แปลง JSON ↔ Object อัตโนมัติ ลด Boilerplate
  • Date/Time: JSON ไม่มี Type Date ให้ Parse String แล้ว Convert เอง (ISO 8601)

ตัวอย่างใช้ Gson (แนะนำสำหรับ Production)

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

// Model
class GeoData {
    String id, name, gender, latitude, longitude;
}

class Response {
    List geodata;
}

// Parse
Gson gson = new Gson();
Response response = gson.fromJson(jsonString, Response.class);
String name = response.geodata.get(0).name;