Course – RWSB – NPI (cat=REST/Spring/Spring Boot)
announcement - icon

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June, after which it will permanently increase by 50$

>> GET ACCESS NOW

Course – LS – NPI (cat=JSON/Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – LS (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

1. Overview

As we know, the HttpClient class, introduced in Java 11, helps to request HTTP resources from a server. It supports both synchronous and asynchronous programming patterns.

In this tutorial, we’ll explore different ways of mapping HTTP responses from HttpClient to the Plain Old Java Object (POJO) classes.

2. Example Setup

Let’s write a simple program, Todo. The program will consume a fake REST API. We’ll perform a GET request and later manipulate the response.

2.1. Maven Dependencies

We’ll manage our dependencies with Maven. Let’s add Gson and Jackson dependencies to our pom.xml to make the libraries available for use in our program:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>
        
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.16.0</version>
</dependency>

2.2. Sample Project

In this tutorial, we’ll use a fake REST API for fast prototyping.

First, let’s view the sample API response when the GET request is invoked:

[
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
]

The sample API returns a JSON response with four properties. The JSON response has more than one object, but we are skipping them for simplicity.

Next, let’s create a POJO class for data binding. The class field matches the JSON data properties. We’ll include constructors, getters, setters, equals(), and toString():

public class Todo {
 
    int userId;
    int id;
    String title;
    boolean completed;
    
    // Standard constructors, getters, setters, equals(), and toString()
}

Then, let’s create a class TodoAppClient that will contain our logic:

public class TodoAppClient { 
    
    ObjectMapper objectMapper = new ObjectMapper();
    Gson gson = new GsonBuilder.create();      
    
    // ...
}

Also, we created new instances of ObjectMapper and GsonBuilder. This makes it accessible and reusable for any method. Creating instances of ObjectMapper inside a method could be an expensive operation.

Finally, we’ll write a method that performs GET requests synchronously on the sample API:

public class TodoAppClient { 

    // ...   

    String sampleApiRequest() throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
          .uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
          .build();
 
        HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
 
        return response.body();
    }

    // ...
}

The ofString() method from BodyHandlers helps convert the response body bytes to String. The response is a JSON String for easy manipulation in the program. In later sections, we’ll explore ways of mapping the response to the POJO class.

Let’s write a unit test for the sampleApiRequest() method:

@Test
public void givenSampleRestApi_whenApiIsConsumedByHttpClient_thenCompareJsonString() throws Exception {
    TodoAppClient sampleApi = new TodoAppClient();
    assertNotNull(sampleApi.sampleApiRequest());
}

The test ascertains that the response from the API call is not null.

3. Map Response to POJO Class Using Jackson

Jackson is a popular Java JSON library. It helps serialize and deserialize JSON for further manipulation. We’ll use it to deserialize the JSON response from the example setup. We’ll map the response to the Todo POJO class.

Let’s enhance the class containing our client-side logic. We’ll create a new method and invoke the sampleApiRequest() method to make the response available for mapping:

public Todo syncJackson() throws Exception {
    
    String response = sampleApiRequest();  
    Todo[] todo = objectMapper.readValue(response, Todo[].class); 
    
    return todo[0];
 }

Next, we declared an array of Todo. Finally, we invoked the readValue() from ObjectMapper to map the JSON String to the POJO class.

Let’s test the method by comparing the returned Todo with an expected new instance of Todo:

@Test
public void givenSampleApiCall_whenResponseIsMappedByJackson_thenCompareMappedResponseByJackson() throws Exception {
    Todo expectedResult = new Todo(1, 1, "delectus aut autem", false); 
    TodoAppClient jacksonTest = new TodoAppClient();
    assertEquals(expectedResult, jacksonTest.syncJackson());
}

The test compares the expected result with the mapped JSON. It ascertains that they are equal.

4. Map Response to POJO Class Using Gson

Gson is a Java library by Google. It’s as popular as Jackson in the Java ecosystem. It helps to map JSON String to Java objects for further processing. This library can also convert Java objects into JSON.

We’ll use it to map JSON response from the example setup to its equivalent POJO class, Todo. Let’s write a new method, syncGson(), in the class containing our logic.

We’ll invoke the sampleApi() to make the JSON String available for deserialization:

public Todo syncGson() throws Exception {
    String response = sampleApiRequest();
    List<Todo> todo = gson.fromJson(response, new TypeToken<List<Todo>>(){}.getType());
    return todo.get(0);
}

First, we created a List of Todo type. Then we invoked the fromJson() method to map the JSON String to the POJO class.

The JSON String is now mapped to the POJO class for further manipulation and processing.

Let’s write a unit test for the syncGson() by comparing an expected result with the returned Todo:

@Test
public void givenSampleApiCall_whenResponseIsMappedByGson_thenCompareMappedGsonJsonResponse() throws Exception {
    Todo expectedResult = new Todo(1, 1, "delectus aut autem", false);   
    TodoAppClient gsonTest = new TodoAppClient();
    assertEquals(expectedResult, gsonTest.syncGson()); 
}

The test shows that the expected result matches the returned value.

5. Asynchronous Call

Now, let’s implement the API call asynchronously. In an asynchronous pattern, threads don’t wait for each other to complete. This programming pattern makes fetching data more robust and scalable.

Let’s fetch the sample API asynchronously and map the JSON response to the POJO class.

5.1. Asynchronous Call and Mapping to POJO Class Using Jackson

In this tutorial, we are using two Java libraries to deserialize the JSON response. Let’s implement asynchronous call mapping with Jackson. First, let’s create a method, readValueJackson(), in TodoAppClient.

The method deserializes the JSON response and maps it to the POJO class:

List<Todo> readValueJackson(String content) {
    try {
        return objectMapper.readValue(content, new TypeReference<List<Todo>>(){});
    } catch (IOException ioe) {
        throw new CompletionException(ioe);
    }
}

Then, let’s add a new method to our logic class:

public Todo asyncJackson() throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
      .build(); 
  
    TodoAppClient todoAppClient = new TodoAppClient();
    List<Todo> todo = HttpClient.newHttpClient()
      .sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenApply(todoAppClient::readValueJackson)
      .get();
 
    return todo.get(0);
}

The method makes asynchronous GET requests and maps the JSON String to the POJO class by invoking the readValueJackson().

Finally, let’s write a unit test to compare the deserialized JSON response with an expected instance of Todo:

@Test
public void givenSampleApiAsyncCall_whenResponseIsMappedByJackson_thenCompareMappedJacksonJsonResponse() throws Exception {
    Todo expectedResult = new Todo(1, 1, "delectus aut autem", false);  
    TodoAppClient sampleAsyncJackson = new TodoAppClient();
    assertEquals(expectedResult, sampleAsyncJackson.asyncJackson());
}

The expected result and the mapped JSON response are equal.

5.2. Asynchronous Call and Mapping to POJO Class Using Gson

Let’s further enhance the program by mapping asynchronous JSON responses to the POJO class. First, let’s create  a method to deserialize the JSON String in TodoAppClient:

List<Todo> readValueGson(String content) {
    return gson.fromJson(content, new TypeToken<List<Todo>>(){}.getType());
}

Next, let’s add a new method to the class containing our program logic:

public Todo asyncGson() throws Exception {
    HttpClient client = HttpClient.newHttpClient();
    HttpRequest request = HttpRequest.newBuilder()
      .uri(URI.create("https://jsonplaceholder.typicode.com/todos"))
      .build();
    TodoAppClient todoAppClient = new TodoAppClient();
    List<Todo> todo = HttpClient.newHttpClient()
      .sendAsync(request, BodyHandlers.ofString())
      .thenApply(HttpResponse::body)
      .thenApply(todoAppClient::readValueGson)
      .get();
  
    return todo.get(0);
}

The method makes an asynchronous GET request and maps the JSON response to the POJO class. Finally, we invoked readValueGson() to perform the process of mapping the response to the POJO class.

Let’s write a unit test. We’ll compare the expected new instance of Todo with the mapped response:

@Test
public void givenSampleApiAsyncCall_whenResponseIsMappedByGson_thenCompareMappedGsonResponse() throws Exception {
    Todo expectedResult = new Todo(1, 1, "delectus aut autem", false); 
    TodoAppClient sampleAsyncGson = new TodoAppClient();
    assertEquals(expectedResult, sampleAsyncGson.asyncGson());
}

The test shows that the expected result matched the mapped JSON response.

6. Conclusion

In this article, we learned four ways to map JSON responses to a POJO class when using HttpClient. Additionally, we dived into synchronous and asynchronous programming patterns with HttpClient. Furthermore, we used Jackson and Gson library to deserialize JSON response and map JSON String to a POJO class.

As always, the source code for the examples is available over on GitHub.

Course – RWSB – NPI (cat=REST/Spring/Spring Boot)
announcement - icon

Now that the new version of REST With Spring - “REST With Spring Boot” is finally out, the current price will be available until the 22nd of June, after which it will permanently increase by 50$

>> GET ACCESS NOW

Course – LS (cat=REST)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Course – LS (cat=JSON/Jackson)
announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

res – REST (eBook) (cat=REST)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.