Home > Java > javaTutorial > How Do I Iterate Through a JSON Array in Android/Java?

How Do I Iterate Through a JSON Array in Android/Java?

Linda Hamilton
Release: 2024-12-07 16:48:13
Original
521 people have browsed it

How Do I Iterate Through a JSON Array in Android/Java?

Iterating Through JSON Arrays in Android/Java

When interacting with web services or databases, it's common to receive data in JSON format. This data can be structured in hierarchical objects and arrays. Iterating through these data structures is crucial for extracting the information you need.

Specifically, you've inquired about iterating through a JSON array, which is represented as a collection of JSON objects enclosed in square brackets. To access the individual objects within this array, you can utilize the following steps:

1. Convert the JSON String to a JSON Array:

Assuming you have a JSON string containing the array, you can convert it to a JSON array using:

JSONArray array = new JSONArray(json_string);
Copy after login

2. Iterate Using a For Loop:

To loop through each JSON object in the array, you can use the following loop:

for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    int id = row.getInt("id");
    String name = row.getString("name");
}
Copy after login

In this example, the row variable represents the individual JSON objects within the array. You can access their properties (e.g., "id" and "name") using the row.getXXX() methods.

Example:

JSONArray array = new JSONArray("[{ \"id\": 1, \"name\": \"John\" }, { \"id\": 2, \"name\": \"Jane\" }]");

for (int i = 0; i < array.length(); i++) {
    JSONObject row = array.getJSONObject(i);
    int id = row.getInt("id");
    String name = row.getString("name");
    System.out.println(id + ": " + name);
}
Copy after login

Output:

1: John
2: Jane
Copy after login

This code effectively iterates through the JSON array, extracting the "id" and "name" values from each JSON object.

Remember, questions like these often require specific context and code samples. For more detailed scenarios, it's always advisable to provide code snippets and specific error messages encountered along the way.

The above is the detailed content of How Do I Iterate Through a JSON Array in Android/Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template