Java REST API: Tutorial to obtain JSON array efficiently

This tutorial details how to get a JSON array from REST API in a Java application. The article explores two main approaches: using the low-level HttpURLConnection for direct HTTP requests, and leveraging the more modern and powerful Retrofit and RxJava libraries. The tutorial provides complete code examples and emphasizes key practices such as JSON parsing, POJO definition, and error handling, aiming to help developers build robust API clients.
In modern application development, getting data from RESTful APIs is a common task. Many times, APIs will return a list of objects, that is, a JSON array, such as search results, product lists, or user lists. Properly parsing and mapping these JSON arrays to Java objects is key to building robust API clients. This article will delve into two mainstream Java implementations: using the standard library HttpURLConnection and the more advanced Retrofit combined with RxJava.
1. Understand the need to obtain JSON arrays from REST API
When the data structure returned by the API is [...] instead of {...}, it means that we expect to receive an array of JSON objects. For example, an API querying a list of cosmetics might return the following format:
[
{
"_id":"6353e8fe5d63726919402cec",
"code":"0000016615656",
"name":"Lipstick",
"brand":"BrandX"
},
{
"_id":"6353e8fe5d63726919402ced",
"code":"0000016615657",
"name":"Mascara",
"brand":"BrandY"
}
]
Our Java application needs to be able to recognize and parse this array structure and convert it into the form of List
2. Preparation: Define data model (POJO)
No matter which API client you use, you first need to define a Java Plain Old Java Object (POJO) to map the JSON data structure. This POJO should contain all fields in the JSON object. In order to better match the JSON field, especially when the Java field name is inconsistent with the JSON field name, you can use the @SerializedName annotation of the Gson library.
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Cosmetic implements Serializable {
@SerializedName("_id")
@Expose
private String id;
@SerializedName("code")
@Expose
private String code;
@SerializedName("name")
@Expose
private String name;
@SerializedName("brand")
@Expose
private String brand;
//Constructor public Cosmetic(String id, String code, String name, String brand) {
this.id = id;
this.code = code;
this.name = name;
this.brand = brand;
}
// Getters and Setters
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
@Override
public String toString() {
return "Cosmetic{"
"id='" id '\''
", code='" code '\''
", name='" name '\''
", brand='" brand '\''
'}';
}
}
3. Method 1: Use HttpURLConnection to obtain the JSON array
HttpURLConnection is a low-level HTTP client provided by the Java standard library, which can be used directly to send HTTP requests and receive responses. This approach is suitable for simple requests or projects that don't want to introduce additional dependencies.
3.1 Principle overview
The basic process of using HttpURLConnection to obtain a JSON array includes:
- Construct a URL object.
- Open the HttpURLConnection connection.
- Set the request method (GET).
- Get the input stream and read the server response.
- Parse the response content (JSON string) into a list of Java objects.
3.2 Sample code
To parse JSON strings we will use the Gson library. Please make sure to add Gson dependency in pom.xml or build.gradle:
Maven:
<dependency>
<groupid>com.google.code.gson</groupid>
<artifactid>gson</artifactid>
<version>2.10.1</version>
</dependency>
Gradle:
implementation 'com.google.code.gson:gson:2.10.1'
Here is an example of using HttpURLConnection to get a JSON array:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Collections;
import java.util.List;
public class HttpUrlConnectionApiExample {
private static final String API_URL = "http://your-api-base-url/prod/beauty/search"; // Replace with your API address public static List<cosmetic> getCosmeticsArray(String queryField, String queryValue) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
// 1. Construct the URL object and add the query parameter URL url = new URL(API_URL "?" queryField "=" queryValue);
connection = (HttpURLConnection) url.openConnection();
// 2. Set the request method connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/json"); // Tell the server that we expect a JSON response connection.setConnectTimeout(5000); // Connection timeout connection.setReadTimeout(5000); // Read timeout // 3. Get the response code int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 200 OK
// 4. Read the response stream reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
// 5. Use Gson to parse JSON array Gson gson = new Gson();
// For generic types (such as List<cosmetic>), you need to use TypeToken to get the correct Type
Type cosmeticListType = new TypeToken<list>>() {}.getType();
return gson.fromJson(response.toString(), cosmeticListType);
} else {
System.err.println("API request failed, response code: " responseCode);
// The error stream can be read and printed if (connection.getErrorStream() != null) {
reader = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
StringBuilder errorResponse = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
errorResponse.append(line);
}
System.err.println("Error details: " errorResponse.toString());
}
}
} catch (IOException e) {
System.err.println("An error occurred while connecting to the network or reading data: " e.getMessage());
e.printStackTrace();
} finally {
// Make sure the resource is closed if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
return Collections.emptyList(); // Returning an empty list indicates failure or no results}
public static void main(String[] args) {
// Assume the API query parameters are "name" and "Lipstick"
List<cosmetic> cosmetics = getCosmeticsArray("name", "Lipstick");
if (!cosmetics.isEmpty()) {
System.out.println("Successfully obtained the cosmetics list:");
for (Cosmetic cosmetic : cosmetics) {
System.out.println(cosmetic);
}
} else {
System.out.println("Cosmetics were not obtained or the request failed.");
}
}
}</cosmetic></list></cosmetic></cosmetic>
3.3 Things to note
- Manual resource management: Need to manually manage the opening and closing of connections and the closing of input/output streams.
- Error handling: HTTP response codes must be explicitly checked and various IOExceptions handled.
- Synchronous blocking: HttpURLConnection is synchronously blocking by default, and calling it directly in the main thread will block the UI. In actual applications, it should be placed in a separate thread or executed using ExecutorService.
- Security: HttpURLConnection itself is secure, but if not handled properly (such as not verifying SSL certificates), it can introduce security risks. "Safety" here refers more to the robustness of the code and its ability to handle complex scenarios.
4. Method 2: Use Retrofit and RxJava to obtain JSON array
Retrofit is a type-safe HTTP client that converts REST APIs into Java interfaces. Combined with RxJava, a powerful asynchronous and reactive programming model can be implemented, greatly simplifying API calls and result processing. This is the more recommended way in modern Java and Android applications.
4.1 Principle overview
Process of obtaining JSON array using Retrofit and RxJava:
- Define the Retrofit service interface: declare a method whose return type is Single
- > or Call
- >.
- Build a Retrofit instance: configure baseUrl, JSON converter (such as GsonConverterFactory) and Call Adapter (such as RxJava2CallAdapterFactory).
- Create a service instance: Create an implementation of the service interface through a Retrofit instance.
- Initiate an API call: call the service method and subscribe to the Single returned by it or perform a Call.
4.2 Dependency configuration
Please make sure to add the following dependencies in pom.xml or build.gradle:
Maven:
<dependency>
<groupid>com.squareup.retrofit2</groupid>
<artifactid>retrofit</artifactid>
<version>2.9.0</version>
</dependency>
<dependency>
<groupid>com.squareup.retrofit2</groupid>
<artifactid>converter-gson</artifactid>
<version>2.9.0</version>
</dependency>
<dependency>
<groupid>com.squareup.retrofit2</groupid>
<artifactid>adapter-rxjava2</artifactid>
<version>2.9.0</version>
</dependency>
<dependency>
<groupid>io.reactivex.rxjava2</groupid>
<artifactid>rxjava</artifactid>
<version>2.2.21</version>
</dependency>
<dependency>
<groupid>io.reactivex.rxjava2</groupid>
<artifactid>rxandroid</artifactid>
<version>2.1.1</version>
</dependency>
Gradle:
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0' implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0' implementation 'io.reactivex.rxjava2:rxjava:2.2.21' implementation 'io.reactivex.rxjava2:rxandroid:2.1.1' // If it is an Android project
4.3 Sample code
First, define the Retrofit service interface:
import io.reactivex.Single;
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface CosmeticsService {
// Method to obtain a single Cosmetic object (if supported by the API)
@GET("/prod/beauty/{field}")
Single<cosmetic> getByName(@Query("name") String name);
// Method to obtain array of Cosmetic objects // Note that the return type is List<cosmetic>
@GET("/prod/beauty/search") // Assume this is the API path to get the list. Single<list>> searchCosmetics(@Query("queryField") String queryField, @Query("queryValue") String queryValue);
}</list></cosmetic></cosmetic>
Then, make the API call:
import io.reactivex.Single;
import io.reactivex.SingleObserver;
import io.reactivex.android.schedulers.AndroidSchedulers; // Android only
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import java.util.List;
import java.util.concurrent.CountDownLatch; // Used for desktop applications to simulate asynchronous waiting public class RetrofitRxJavaApiExample {
private static final String BASE_URL = "http://your-api-base-url/"; // Replace with your API base URL
private retrofit retrofit;
private CosmeticsService service;
private CompositeDisposable compositeDisposable = new CompositeDisposable();
public RetrofitRxJavaApiExample() {
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service = retrofit.create(CosmeticsService.class);
}
public void fetchCosmeticsList(String queryField, String queryValue) {
// Call the method to get the Cosmetic list Single<list>> callSync = service.searchCosmetics(queryField, queryValue);
callSync.subscribeOn(Schedulers.io()) // Perform network requests on the IO thread // .observeOn(AndroidSchedulers.mainThread()) // If it is an Android application, switch to the main thread to update the UI
.observeOn(Schedulers.computation()) // For non-Android applications, you can switch to other threads to process results.onErrorReturn(throwable -> {
System.err.println("API request error: " throwable.getMessage());
throwable.printStackTrace();
return Collections.emptyList(); //return empty list on error})
.subscribe(new SingleObserver<list>>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d); //Manage Disposable to prevent memory leaks}
@Override
public void onSuccess(List<cosmetic> cosmetics) {
if (!cosmetics.isEmpty()) {
System.out.println("Successfully obtained the cosmetics list:");
for (Cosmetic cosmetic : cosmetics) {
System.out.println(cosmetic);
}
} else {
System.out.println("No cosmetics obtained or the result is empty.");
}
// If it is a desktop application, some mechanism is needed to notify the main thread that the operation is completed // For example, use CountDownLatch
// latch.countDown();
}
@Override
public void onError(Throwable e) {
System.err.println("An error occurred during subscription processing: " e.getMessage());
e.printStackTrace();
// latch.countDown(); // The same notification is completed}
});
}
// Called when the application exits or the component is destroyed to clean up resources public void dispose() {
compositeDisposable.clear();
}
public static void main(String[] args) throws InterruptedException {
RetrofitRxJavaApiExample apiExample = new RetrofitRxJavaApiExample();
CountDownLatch latch = new CountDownLatch(1); // Used to simulate asynchronous waiting, in desktop applications // Assume that the API query parameters are "name" and "Lipstick"
apiExample.fetchCosmeticsList("name", "Lipstick");
// In desktop applications, the main thread may need to wait for the asynchronous operation to complete // In Android, there is usually no need to wait explicitly because the UI will be updated in the callback latch.await(10, java.util.concurrent.TimeUnit.SECONDS); // Wait up to 10 seconds apiExample.dispose(); // Clean up resources }
}</cosmetic></list></list>
4.4 Precautions
- Type safety: Retrofit provides strong type safety through interface definition, reducing runtime errors.
- Asynchronous processing: RxJava provides a powerful asynchronous programming model, and thread switching can be easily managed through subscribeOn and observeOn.
- Error handling: RxJava operators (such as onErrorReturn) make error handling more elegant and chainable.
- Resource management: Use CompositeDisposable to manage Disposable objects to prevent memory leaks, especially in Android applications.
- Testability: The interface design makes the API service easier to perform unit testing and integration testing.
5. Selection and use of JSON parsing library
In the examples in this article, Google's Gson library is used for JSON parsing. Gson is a powerful and easy-to-use Java library that can serialize Java objects to JSON and vice versa.
- Single object parsing: gson.fromJson(jsonString, Cosmetic.class)
- Object list parsing: gson.fromJson(jsonString, new TypeToken
- >() {}.getType())
TypeToken is the key to handling Java generic type erasure. Since Java erases generic information at runtime, List
6. Error handling and robustness
Regardless of the approach, a robust API client must handle various error conditions gracefully:
- Network connection error: `IOException
The above is the detailed content of Java REST API: Tutorial to obtain JSON array efficiently. 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
20518
7
13631
4
How to configure Spark distributed computing environment in Java_Java big data processing
Mar 09, 2026 pm 08:45 PM
Spark cannot run in local mode, ClassNotFoundException: org.apache.spark.sql.SparkSession. This is the most common first step of getting stuck: even the dependencies are not correct. Only spark-core_2.12 is written in Maven, but spark-sql_2.12 is not added. SparkSession crashes as soon as it is built. The Scala version must strictly match the official Spark compiled version - Spark3.4.x uses Scala2.12 by default. If you use spark-sqljar of 2.13, the class loader cannot directly find the main class. Practical advice: Go to mvnre
How to safely map user-entered weekday string to integer value and implement date offset operation in Java
Mar 09, 2026 pm 09:43 PM
This article introduces a concise and maintainable way to map the weekday string (such as "Monday") to the corresponding serial number (1-7), and use the modulo operation to realize the forward and backward offset of any number of days (such as Monday plus 4 days to get Friday), avoiding lengthy if chains and hard-coded logic.
How to generate a list of duplicate elements using Java's Collections.nCopies_Initialization tips
Mar 06, 2026 am 06:24 AM
Collections.nCopies returns an immutable view. Calling add/remove will throw UnsupportedOperationException; it needs to be wrapped with newArrayList() to modify it, and it is disabled for mutable objects.
How to use Homebrew to install Java on Mac_A must-have Java tool chain for developers
Mar 09, 2026 pm 09:48 PM
Homebrew installs the latest stable version of openjdk (such as JDK22) by default, not the LTS version; you need to explicitly execute brewinstallopenjdk@17 or brewinstallopenjdk@21 to install the LTS version, and manually configure PATH and JAVA_HOME to be correctly recognized by the system and IDE.
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 correctly implement runtime file writing in Java applications (avoiding JAR internal write failures)
Mar 09, 2026 pm 07:57 PM
After a Java application is packaged as a JAR, data cannot be written directly to the resources in the JAR package (such as test.txt) because the JAR is essentially a read-only ZIP archive; the correct approach is to write variable data to an external path (such as a user directory, a temporary directory, or a configuration-specified path).
What is the underlying principle of array expansion in Java_Java memory dynamic adjustment analysis
Mar 09, 2026 pm 09:45 PM
ArrayList.add() triggers expansion because grow() is called when size is equal to elementData.length. The first add allocates 10 capacity, and subsequent expansion is 1.5 times and not less than the minimum requirement, relying on delayed initialization and System.arraycopy optimization.
How to safely read a line of integer input in Java and avoid Scanner blocking
Mar 06, 2026 am 06:21 AM
This article introduces typical blocking problems when using Scanner to read multiple integers in a single line. It points out that hasNextInt() will wait indefinitely when there is no subsequent input, and recommends a safe alternative with nextLine() string splitting as the core.





