Giới thiệu
Parse mảng JSON users thành List<UserInfo> với 2 trường: name, email. Hiển thị phần tử đầu tiên.
Code (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");
List list = new ArrayList<>();
for (int i = 0; i < array.length(); i++) {
JSONObject u = array.getJSONObject(i);
list.add(new UserInfo(u.getString("name"), u.getString("email")));
}
if (!list.isEmpty()) {
UserInfo first = list.get(0);
textView.setText("Email: " + first.email + "\nName: " + first.name);
}
} catch (Exception e) {
e.printStackTrace();
textView.setText("Lỗi parse");
}
},
error -> textView.setText("Lỗi mạng")
);
queue.add(request);
}
private static class UserInfo {
String name, email;
UserInfo(String name, String email) { this.name = name; this.email = email; }
}
}
Mở rộng thực tế
- Dùng Gson:
Type listType = new TypeToken<List<UserInfo>>(){}.getType(); List<UserInfo> list = new Gson().fromJson(jsonArrayString, listType); - Hiển thị danh sách bằng RecyclerView + Adapter.
- Thêm annotation
@SerializedNamenếu tên field JSON khác tên field Java.