To use HttpClient with JSON parsing in Java, the most common approach is to combine the standard java.net.http.HttpClient with a JSON library like Jackson or Gson.
While HttpClient doesn’t have a built-in JSON parser, you can map the response body string to a Java object.
Using Jackson (Recommended)
Jackson is a powerful and widely-used library in the Java ecosystem. Here is how you can fetch a JSON response and parse it into a POJO (Plain Old Java Object).
First, define your data model:
public record Post(int userId, int id, String title, String body) {}
Then, use the HttpClient to fetch the data and ObjectMapper to parse it:
package org.kodejava.httpclient;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class HttpClientJsonExample {
public static void main(String[] args) {
HttpClient client = HttpClient.newHttpClient();
ObjectMapper mapper = new ObjectMapper();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://jsonplaceholder.typicode.com/posts/1"))
.header("Accept", "application/json")
.build();
try {
// Send request and get response as a String
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() == 200) {
// Parse the JSON string into the Post object
Post post = mapper.readValue(response.body(), Post.class);
System.out.println("Post Title: " + post.title());
System.out.println("Post Body: " + post.body());
} else {
System.err.println("Error: " + response.statusCode());
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Tip: Custom BodyHandler
If you find yourself parsing JSON frequently, you can implement a custom HttpResponse.BodyHandler to handle the conversion automatically.
public static <T> HttpResponse.BodyHandler<T> asJson(Class<T> targetType) {
return responseInfo -> HttpResponse.BodySubscribers.mapping(
HttpResponse.BodySubscribers.ofString(StandardCharsets.UTF_8),
body -> {
try {
return new ObjectMapper().readValue(body, targetType);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
}
// Usage:
// HttpResponse<Post> response = client.send(request, asJson(Post.class));
// Post post = response.body();
Dependencies
Ensure you have the Jackson dependency in your pom.xml:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.18.2</version>
</dependency>
This approach keeps your networking logic clean while leveraging the robustness of proven JSON libraries
