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

Cách sử dụng JSONObject để phân tích JSON trong Android

Hướng dẫn này minh họa cách sử dụng JSONObject để phân tích (parse) chuỗi JSON trong Android. JSONObject là lớp cốt lõi trong gói org.json của Android, cho phép truy xuất dữ liệu JSON một cách đơn giản và hiệu quả.

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

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

Mở Android Studio, chọn File → New Project và điền thông tin cần thiết.

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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        android:textStyle="bold"
        android:textSize="24sp"
        android:layout_centerInParent="true"/>

</RelativeLayout>

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

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {
    // Chuỗi JSON mẫu - lưu ý escape dấu nháy kép
    public static final String JSON_STRING = "{\"Employee\":{\"Name\":\"Niyaz\",\"Salary\":56000}}";

    TextView textView;

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

        textView = findViewById(R.id.textView);

        try {
            // Parse JSON: lấy object "Employee" từ chuỗi gốc
            JSONObject emp = (new JSONObject(JSON_STRING)).getJSONObject("Employee");

            // Trích xuất các trường
            String empName = emp.getString("Name");
            int empSalary = emp.getInt("Salary");

            // Hiển thị kết quả
            String result = "Employee Name: " + empName + "\n" + "Employee Salary: " + empSalary;
            textView.setText(result);

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

Bước 4: Cấu hình 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>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Ứng dụng sẽ parse chuỗi JSON cứng (hardcoded) và hiển thị tên và lương nhân viên lên TextView.

Cách sử dụng JSONObject để phân tích JSON trong Android

Giải thích quan trọng

  • JSONObject(String): Tạo đối tượng từ chuỗi JSON
  • getJSONObject(key): Lấy đối tượng JSON con
  • getString(key), getInt(key), getBoolean(key), getDouble(key): Trích xuất giá trị theo kiểu dữ liệu
  • JSONException: Luôn bắt ngoại lệ này khi parse - JSON có thể sai định dạng

Mở rộng thực tế

Trong ứng dụng thật, chuỗi JSON thường đến từ:

  • API response (Retrofit, Volley, OkHttp)
  • File JSON trong assets hoặc raw
  • SharedPreferences

Với JSON phức tạp (mảng lồng nhau), hãy kết hợp JSONArray và duyệt qua từng phần tử.