How to iterate through a JSONArray in Java to retrieve data and compare it?
To iterate over a JSONArray in Java, retrieve data and compare it, follow these steps:
- Import the necessary dependencies, such as the json library (such as fastjson or json-simple).
- Parse the JSON string into a JSONArray object using the json library.
- Traverse through the JSONArray object and retrieve each JSONObject one by one.
- Retrieve the fields to be compared in the JSONObject and perform the comparison operation.
The sample code is shown below (using the fastjson library):
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
public class Main {
public static void main(String[] args) {
// 假设json字符串为 [{"name": "Alice", "age": 25}, {"name": "Bob", "age": 30}]
String jsonString = "[{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 30}]";
// 解析为JSONArray对象
JSONArray jsonArray = JSONArray.parseArray(jsonString);
// 遍历JSONArray对象
for (int i = 0; i < jsonArray.size(); i++) {
// 获取JSONObject
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 获取需要比对的字段
String name = jsonObject.getString("name");
int age = jsonObject.getInteger("age");
// 比对操作
if (name.equals("Alice")) {
System.out.println("Alice's age is " + age);
} else if (name.equals("Bob")) {
System.out.println("Bob's age is " + age);
}
}
}
}
The code above demonstrates how to loop through a JSONArray to retrieve data and perform comparison operations. Depending on the specific situation, the comparison logic can be modified as needed.