Java
javaTutorial
Efficient parsing of JSON object arrays in Java: extracting specific fields from complex JSON responses
Efficient parsing of JSON object arrays in Java: extracting specific fields from complex JSON responses

This article details how to parse a `JSONArray` containing `JSONObject` in Java to extract specific fields such as `id` and `result` from a JSON response like `{"result":[{"result":"success","id":"345"}]}`. The tutorial covers the mapping method using traditional iteration combined with POJO (Plain Old Java Object), as well as the strategy of using Java Stream API to achieve more concise and functional parsing, aiming to provide clear and practical JSON data processing guidance.
In modern web service interactions, processing JSON-formatted data responses is a common task. Sometimes, the JSON structure returned by the server will contain an array with multiple JSON objects nested in it. For example, the following is a typical response format:
{"result":[{"result":"success","id":"345"}]}
Our goal is to extract the id and result field values of each inner JSONObject from such a response. This article will introduce two efficient ways to achieve this goal in Java.
Understanding JSON response structure
First, we need to clarify the structure of the above JSON response:
- The outermost layer is a JSONObject.
- This JSONObject contains a field with the key "result".
- The value of the "result" field is a JSONArray.
- JSONArray contains one or more JSONObjects.
- Each inner JSONObject contains "result" and "id" fields.
Therefore, the parsing process needs to be carried out layer by layer: first obtain the outer JSONObject, then obtain the JSONArray, and finally traverse each JSONObject in the JSONArray to extract the required data.
Method 1: Traditional iteration and POJO mapping
This method maps the structure of the JSON object by defining a Java object (POJO or Java 16 record), and then parses the JSONArray using traditional loop iteration.
1. Define data model (POJO/Record)
To easily store and manipulate data extracted from JSON, we can define a Java class or record (Java 16) to represent the internal JSON object. Using records can greatly simplify your code.
// Java 16 record
public record Result(String result, int id) {}
// Or, traditional Java class/*
public class Result {
private String result;
private int id;
public Result(String result, int id) {
this.result = result;
this.id = id;
}
// Getters and Setters (omitted)
// toString method (omitted)
}
*/
2. Analysis and implementation
Next, we will use the org.json library to parse JSON strings. First get the top-level JSONObject, then get the JSONArray by key "result". Finally, iterate over the JSONArray, convert each JSONObject into a Result object and collect it into a list.
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class JsonParserTraditional {
// Java 16 record
public record Result(String result, int id) {}
public static void main(String[] args) {
String response = """
{"result":[{"result":"success","id":"345"},{"result":"failure","id":"346"}]}
"""; // An object has been added to the example to better demonstrate array traversal try {
// 1. Convert the response string to JSONObject
JSONObject jsonResponse = new JSONObject(response);
// 2. Get the JSONArray with the key "result"
JSONArray jsonArray = jsonResponse.getJSONArray("result");
// 3. Create a list to store the parsed Result object List<result> results = new ArrayList();
// 4. Traverse JSONArray and parse each JSONObject
for (int i = 0; i <p> <strong>Output example:</strong></p>
<pre class="brush:php;toolbar:false"> Result[result=success, id=345]
Result[result=failure, id=346]
Method 2: Using Java Stream API
The Stream API introduced in Java 8 provides a simpler and more functional way to handle collection data. We can convert the JSONArray into a stream and then use chained operations to convert and filter.
1. Stream API analysis and implementation
To convert a JSONArray into a stream, we can make use of the StreamSupport utility class, which allows us to create a stream from a Spliterator.
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.List;
import java.util.stream.StreamSupport;
public class JsonParserStreamAPI {
// Java 16 record
public record Result(String result, int id) {}
public static void main(String[] args) {
String response = """
{"result":[{"result":"success","id":"345"},{"result":"failure","id":"346"}]}
""";
try {
// 1. Convert the response string to JSONObject
JSONObject jsonResponse = new JSONObject(response);
// 2. Get the JSONArray with the key "result"
JSONArray jsonArray = jsonResponse.getJSONArray("result");
// 3. Use Stream API to parse JSONArray
List<result> results = StreamSupport.stream(jsonArray.spliterator(), false) // Convert JSONArray to Stream<object>
.map(JSONObject.class::cast) // Convert each element in Stream<object> to JSONObject
.map(jsonObject -> // Map each JSONObject to a Result object new Result(jsonObject.getString("result"), jsonObject.getInt("id"))
)
.toList(); // Java 16: Collect streams into immutable lists; for Java 8-15, use .collect(Collectors.toList())
// 4. Print the parsing results results.forEach(System.out::println);
} catch (org.json.JSONException e) {
System.err.println("JSON parsing error: " e.getMessage());
}
}
}</object></object></result>
Output example:
Result[result=success, id=345] Result[result=failure, id=346]
Summary and Notes
- Dependency management : The above example uses the org.json library. In the Maven project, you need to add the following dependencies in pom.xml:
<dependency> <groupid>org.json</groupid> <artifactid>json</artifactid> <version>20231013</version> <!-- Use the latest version --> </dependency>For more complex JSON processing, you can also consider using more powerful libraries such as Jackson or Gson.
- Error handling : In actual applications, be sure to add try-catch blocks to catch org.json.JSONException. The JSON structure may not always be as expected, for example a key may not exist, or the value type may not match, which can lead to runtime exceptions.
- Java version :
- The record type is a feature introduced in Java 16 and above. If you use an older version of Java, use traditional class definition POJOs instead.
- List.toList() is a new method of Stream interface in Java 16 and above. For Java 8-15, collect(Collectors.toList()) should be used.
- Selection method :
- The traditional iteration method is more intuitive, easy to understand, and suitable for various Java versions.
- The Stream API method code is more concise and reflects the style of functional programming. Its advantages are more obvious especially when complex data conversion, filtering and aggregation are required. But for beginners, it may take some getting used to.
- Type conversion : When extracting values from JSONObject, make sure to use the correct methods (such as getString(), getInt(), getBoolean(), etc.) to avoid JSONException.
With the above two methods, you can parse complex JSON responses in Java flexibly and efficiently and extract the required data from them. Which method you choose depends on your project needs, team preferences, and the version of Java you are using.
The above is the detailed content of Efficient parsing of JSON object arrays in Java: extracting specific fields from complex JSON responses. For more information, please follow other related articles on the PHP Chinese website!
Hot AI Tools
Undress AI Tool
Undress images for free
AI Clothes Remover
Online AI tool for removing clothes from photos.
Undresser.AI Undress
AI-powered app for creating realistic nude photos
ArtGPT
AI image generator for creative art from text prompts.
Stock Market GPT
AI powered investment research for smarter decisions
Hot Article
Popular tool
Notepad++7.3.1
Easy-to-use and free code editor
SublimeText3 Chinese version
Chinese version, very easy to use
Zend Studio 13.0.1
Powerful PHP integrated development environment
Dreamweaver CS6
Visual web development tools
SublimeText3 Mac version
God-level code editing software (SublimeText3)
Hot Topics
20524
7
13636
4
What is exception masking (Suppressed Exceptions) in Java_Multiple resource shutdown exception handling
Mar 10, 2026 pm 06:57 PM
What is SuppressedException: It is not "swallowed", but actively archived by the JVM. SuppressedException is not an exception loss, but the JVM quietly attaches the secondary exception to the main exception under the premise that "only one exception must be thrown" for you to verify afterwards. It is automatically triggered by the JVM in only two scenarios: one is that the resource closure in try-with-resources fails, and the other is that you manually call addSuppressed() in finally. The key difference is: the former is fully automatic and safe; the latter requires you to keep it to yourself, and it can be written as shadowing if you are not careful. try-
How to configure Java's log output environment_Logback and Log4j2 integration solution
Mar 10, 2026 pm 08:39 PM
They cannot be used together - Logback and Log4j2 are mutually exclusive, and SLF4J only allows one binding to take effect; if they exist at the same time, a warning will be triggered and one of them will be randomly selected, resulting in log loss or abnormal behavior. A unified appearance and single implementation are required.
How to hot deploy Java applications in IDEA_JRebel plug-in installation and activation tutorial
Mar 10, 2026 pm 08:01 PM
JRebel has basically failed in modern Java development because of its underlying mechanism conflicts with the Java9 module system, SpringBoot2.4 and mainstream IDEs, while IDEA's built-in HotSwap spring-boot-devtools combination is more stable and reliable.
What is the core role of the collection framework in Java_Analysis of the original intention of Java collection design
Mar 11, 2026 pm 09:01 PM
The core of the Java collection framework is to solve the three major shortcomings of fixed array length, type insecurity, and redundant operations; it abstracts data relationships through interfaces (Collection is a "bundle of things", Map is "mapping rules"), and generics ensure compilation-time type safety, but implementation class switching may cause implicit performance degradation.
How to configure Java hotkeys in IntelliJ IDEA_Common shortcut key customization guide
Mar 10, 2026 pm 08:06 PM
In IDEA, Ctrl Alt L defaults to "ReformatCode", which can be changed to other operations: first check for conflicts in the Keymap, then remove the original binding and add a new shortcut key for the target operation; pay attention to the focus position, file type and plug-in interference; Mac needs to troubleshoot system-level interception; when team collaboration, the Scheme should be unified and the settings should be synchronized with SettingsRepository.
How to deploy Java production environment on Windows Server_Security enhancement and service-oriented configuration
Mar 11, 2026 pm 07:18 PM
The boundary between Java version selection and JRE/JDK must be clearly defined in the production environment. Do not use JDK. JRE must be installed on Windows Server—unless you really need diagnostic tools such as jps and jstack to run in the service process. The java.exe and javaw.exe that come with the JDK have the same behavior, but the extra bin directory in the JDK will increase the attack surface. Especially when misconfigured PATH causes the script to call javac.exe, it may be used to execute compiled malicious payloads. Download the build with jdk-xx.jre suffix from https://adoptium.net/ (such as temurin-17.0.2 8-jre), which is not the jdk package installation path.
JavaFX: Copy string contents to system clipboard
Mar 13, 2026 am 04:12 AM
This article details how to copy string contents to the system clipboard in a JavaFX application. By utilizing the javafx.scene.input.Clipboard and javafx.scene.input.ClipboardContent classes, developers can easily implement clipboard operations on text data. The article provides clear sample code and usage guidelines to ensure that readers can quickly master and apply this feature in their own projects to improve user experience.
Optimize the Controller layer: introduce DTO mapping and service calling abstraction layer
Apr 03, 2026 am 10:00 AM
This article discusses the introduction of an abstraction layer between the Controller and business services in order to solve the problems of overloaded responsibilities and code duplication in the Controller layer in Web application development. This layer is mainly responsible for the mapping of request DTOs and service input DTOs, service calls, and the mapping of service output DTOs and response DTOs. It achieves generalization through generic and functional programming, thereby improving the cleanliness, maintainability and testability of the code.





