Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách đọc mảng JSON theo thứ tự ngược trên Android

Giới thiệu

Parse JSON từ server, duyệt mảng users từ cuối về đầu (index length-1 đến 0), tạo object UserInfo và hiển thị name.

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");
                    StringBuilder sb = new StringBuilder();

                    for (int i = array.length() - 1; i >= 0; i--) {
                        JSONObject user = array.getJSONObject(i);
                        String name = user.getString("name");
                        sb.append(name).append("\n");
                    }

                    textView.setText("Tên theo thứ tự ngược:\n" + sb.toString());
                } 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;
        UserInfo(String name) { this.name = name; }
    }
}

Quyền

<uses-permission android:name="android.permission.INTERNET" />

Giải thích

  • Vòng lặp for (int i = array.length() - 1; i >= 0; i--) duyệt ngược.
  • Tương tự có thể dùng Collections.reverse(list) sau khi add tất cả vào list.
  • Class UserInfo ở đây chỉ demo, thực tế có thêm id, email...