Giới thiệu
Demo parse JSON từ server bằng Volley, chuyển từng object trong mảng users thành instance của class UserInfo (POJO).
Các bước thực hiện
Bước 1: Project & Dependency
Thêm Volley vào build.gradle.
Bước 2: Giao diện
<TextView
android:id="@+id/text"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:textSize="20sp" />
Bước 3: Model & Logic (MainActivity.java)
public class MainActivity extends AppCompatActivity {
private TextView textView;
private RequestQueue queue;
private static final String URL = "https://mocky.io/v2/597c41390f0000d002f4dbd1";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.text);
queue = Volley.newRequestQueue(this);
StringRequest request = new StringRequest(Request.Method.GET, URL,
response -> {
try {
JSONObject obj = new JSONObject(response);
JSONArray array = obj.getJSONArray("users");
// Chỉ lấy user đầu tiên để demo
if (array.length() > 0) {
JSONObject user = array.getJSONObject(0);
UserInfo userInfo = new UserInfo(user.getString("name"));
textView.setText("Tên từ object: " + userInfo.getName());
}
} catch (Exception e) {
e.printStackTrace();
textView.setText("Lỗi parse");
}
},
error -> textView.setText("Lỗi mạng")
);
queue.add(request);
}
// POJO class
private static class UserInfo {
private String name;
UserInfo(String name) { this.name = name; }
String getName() { return name; }
}
}
Bước 4: Quyền Internet
<uses-permission android:name="android.permission.INTERNET" />
Mở rộng thực tế
- Thêm các field: email, id, gender... vào class UserInfo.
- Dùng thư viện Gson hoặc Moshi để tự động mapping JSON → Object.
- Lưu danh sách vào
List<UserInfo>để hiển thị RecyclerView.