BAEL-5952-Java HttpClient - Map Json Response to Java Class (#13234)

* Java HttpClient - Map Json Response to Java Class

* BAEL-5952-Java HttpClient - Map Json Response to Java Class

* BAEL-5952-Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class

* Java HttpClient - Map Json Response to Java Class
This commit is contained in:
Michael Olayemi 2023-01-27 08:22:01 +01:00 committed by GitHub
parent 3b521d448f
commit b5d8f4e93c
4 changed files with 241 additions and 0 deletions

View File

@ -14,6 +14,20 @@
<version>1.0.0-SNAPSHOT</version>
<relativePath>../../pom.xml</relativePath>
</parent>
<dependencies>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
</dependencies>
<build>
<plugins>
@ -32,6 +46,8 @@
<properties>
<maven.compiler.source.version>11</maven.compiler.source.version>
<maven.compiler.target.version>11</maven.compiler.target.version>
<jackson.version>2.14.1</jackson.version>
<gson.version>2.10</gson.version>
</properties>
</project>

View File

@ -0,0 +1,73 @@
package com.baeldung.httppojo;
import java.util.Objects;
public class Todo {
int userId;
int id;
String title;
boolean completed;
public Todo() {
}
public Todo(int userId, int id, String title, boolean completed) {
this.userId = userId;
this.id = id;
this.title = title;
this.completed = completed;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public boolean isCompleted() {
return completed;
}
public void setCompleted(boolean completed) {
this.completed = completed;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Todo todo = (Todo) o;
return userId == todo.userId && id == todo.id && completed == todo.completed && Objects.equals(title, todo.title);
}
@Override
public int hashCode() {
return Objects.hash(userId, id, title, completed);
}
@Override
public String toString() {
return "{" + "userId=" + userId + ", id=" + id + ", title='" + title + '\'' + ", completed=" + completed + '}';
}
}

View File

@ -0,0 +1,107 @@
package com.baeldung.httppojo;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.util.List;
import java.util.concurrent.CompletionException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
public class TodoAppClient {
ObjectMapper objectMapper = new ObjectMapper();
Gson gson = new GsonBuilder().create();
public 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();
}
public Todo syncGson() throws Exception {
String response = sampleApiRequest();
List<Todo> todo = gson.fromJson(response, new TypeToken<List<Todo>>() {
}.getType());
return todo.get(1);
}
public Todo syncJackson() throws Exception {
String response = sampleApiRequest();
Todo[] todo = objectMapper.readValue(response, Todo[].class);
return todo[1];
}
public Todo asyncJackson() throws Exception {
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(1);
}
public Todo asyncGson() throws Exception {
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(1);
}
List<Todo> readValueJackson(String content) {
try {
return objectMapper.readValue(content, new TypeReference<List<Todo>>() {
});
} catch (IOException ioe) {
throw new CompletionException(ioe);
}
}
List<Todo> readValueGson(String content) {
return gson.fromJson(content, new TypeToken<List<Todo>>() {
}.getType());
}
}

View File

@ -0,0 +1,45 @@
package com.baeldung.httppojo;
import static org.junit.Assert.*;
import org.junit.Test;
public class HttpClientPojoClassUnitTest {
Todo expectedTodo = new Todo(1, 2, "quis ut nam facilis et officia qui", false);
@Test
public void givenSampleApiCall_whenResponseIsMappedByGson_thenCompareResponseMappedByGson() throws Exception {
TodoAppClient sampleGson = new TodoAppClient();
assertEquals(expectedTodo, sampleGson.syncGson());
}
@Test
public void givenSampleApiCall_whenResponseIsMappedByJackson_thenCompareResponseMappedByJackson() throws Exception {
TodoAppClient sampleJackson = new TodoAppClient();
assertEquals(expectedTodo, sampleJackson.syncJackson());
}
@Test
public void givenSampleRestApi_whenApiIsConsumedByHttpClient_thenCompareJsonString() throws Exception {
TodoAppClient sampleTest = new TodoAppClient();
assertNotNull(sampleTest.sampleApiRequest());
}
@Test
public void givenSampleApiAsyncCall_whenResponseIsMappedByJackson_thenCompareResponseMappedByJackson() throws Exception {
TodoAppClient sampleAsynJackson = new TodoAppClient();
assertEquals(expectedTodo, sampleAsynJackson.asyncJackson());
}
@Test
public void givenSampleApiAsyncCall_whenResponseIsMappedByGson_thenCompareResponseMappedByGson() throws Exception {
TodoAppClient sampleAsynGson = new TodoAppClient();
assertEquals(expectedTodo, sampleAsynGson.asyncGson());
}
}