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

วิธี Parse JSON ใน Android

ภาพรวม

ตัวอย่างนี้แสดงวิธีแปลงข้อมูล JSON String ให้เป็นอ็อบเจกต์ Java และดึงค่าที่ต้องการมาแสดงใน TextView

ขั้นตอนที่ 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: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"
    tools:context=".MainActivity">
    <TextView
        android:id="@+id/tvName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:text="Name"
        android:textColor="#000"
        android:textSize="20sp" />
    <TextView
        android:id="@+id/tvSalary"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="80dp"
        android:text="Salary"
        android:textColor="#000"
        android:textSize="20sp" />
</RelativeLayout>

ขั้นตอนที่ 3: เขียนโค้ด MainActivity.java

package com.example.myapplication;
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 {
    String JSON_STRING = "{\"employee\":{\"name\":\"adolf hitler\",\"salary\":65000}}";
    String name, salary;
    TextView employeeName, employeeSalary;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        employeeName = findViewById(R.id.tvName);
        employeeSalary = findViewById(R.id.tvSalary);
        
        try {
            JSONObject obj = new JSONObject(JSON_STRING);
            JSONObject employee = obj.getJSONObject("employee");
            
            name = employee.getString("name");
            salary = employee.getString("salary");
            
            employeeName.setText("Name: " + name);
            employeeSalary.setText("Salary: " + salary);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
}

โครงสร้าง JSON ที่ใช้ในตัวอย่าง

{
  "employee": {
    "name": "adolf hitler",
    "salary": 65000
  }
}

เมธอดสำคัญของ JSONObject

เมธอดคืนค่าคำอธิบาย
getString(key)Stringดึงค่าสตริง
getInt(key)intดึงค่าตัวเลขจำนวนเต็ม
getDouble(key)doubleดึงค่าทศนิยม
getBoolean(key)booleanดึงค่าบูลีน
getJSONObject(key)JSONObjectดึงอ็อบเจกต์ซ้อน
getJSONArray(key)JSONArrayดึงอาร์เรย์
has(key)booleanตรวจสอบว่ามี key นี้หรือไม่
isNull(key)booleanตรวจสอบค่า null

การจัดการ JSONArray

JSONArray array = obj.getJSONArray("users");
for (int i = 0; i < array.length(); i++) {
    JSONObject item = array.getJSONObject(i);
    String name = item.getString("name");
    // ...
}

แนวทางปัจจุบัน: ใช้ Gson / Moshi

สำหรับโปรเจกต์จริง แนะนำให้ใช้ Library แปลง JSON อัตโนมัติ:

// Gson
implementation 'com.google.code.gson:gson:2.10.1'

// Model Class
class Employee {
    String name;
    int salary;
}

// Parse อัตโนมัติ
Employee emp = new Gson().fromJson(jsonString, Employee.class);

การทดสอบ

รันแอป จะแสดง Name: adolf hitler และ Salary: 65000