Giới thiệu
Parse mảng JSON users, lặp qua từng object và lấy trường name (ví dụ chỉ hiển thị name cuối cùng do ghi đè).
Code cải tiến (MainActivity.java)
StringRequest request = new StringRequest(Request.Method.GET, URL,
response -> {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("users");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length(); i++) {
JSONObject user = array.getJSONObject(i);
String name = user.getString("name");
String email = user.getString("email");
sb.append("Name: ").append(name).append(", Email: ").append(email).append("\n");
}
textView.setText(sb.toString());
} catch (Exception e) {
e.printStackTrace();
textView.setText("Lỗi parse");
}
},
error -> textView.setText("Lỗi mạng")
);
queue.add(request);
Cấu trúc JSON mẫu
{
"users": [
{"id": "1", "name": "Alice", "email": "alice@example.com"},
{"id": "2", "name": "Bob", "email": "bob@example.com"}
]
}
Best Practice
- Dùng
StringBuilderđể nối chuỗi hiệu quả. - Map sang class POJO (UserInfo) để code sạch, type-safe.
- Hiển thị bằng RecyclerView thay vì TextView cho danh sách dài.