Giới thiệu
Ví dụ này minh họa cách phân tích (parse) JSONArray trong Android sử dụng thư viện org.json có sẵn.
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: Thiết kế giao diện (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:textSize="24sp"
android:textStyle="bold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Bước 3: Viết code 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 {
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
// Chuỗi JSON mẫu
String strJson = "{ \\"Basic info\\" : [" +
"{\\"Name\\":\\"Mash\\",\\"Age\\":\\"27\\",\\"Gender\\":\\"Male\\"}," +
"{\\"Name\\":\\"Niyaz\\",\\"Age\\":\\"23\\",\\"Gender\\":\\"Male\\"}]}";
String data = "";
try {
JSONObject jsonRootObject = new JSONObject(strJson);
JSONArray jsonArray = jsonRootObject.optJSONArray("Basic info");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
int age = Integer.parseInt(jsonObject.optString("Age"));
String name = jsonObject.optString("Name");
String gender = jsonObject.optString("Gender");
data += "Node " + i + " :\n Name = " + name +
"\n Age = " + age + "\n Gender = " + gender + "\n\n";
}
textView.setText(data);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Các phương thức hữu ích:
optJSONArray(): Trả về null nếu key không tồn tại (an toàn hơngetJSONArray())optString(): Trả về chuỗi rỗng nếu key không tồn tạigetJSONObject(): Lấy object tại vị trí index
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 để xem kết quả parse JSON hiển thị trên TextView.
