Sub topic 11
Sending and parsing JSON with a library
This chapter assumes that you know Java 11 syntax, HttpClient, HTTP methods, headers, and checked exceptions. It also assumes that your project can add external dependencies. Java's HttpClient sends bytes and receives bytes or text. It does not create Java objects from JSON. Use a JSON library such as Jackson for that work.
Add Jackson and model the data
With Maven, add the jackson-databind dependency to your project. Jackson's ObjectMapper converts between JSON text and Java objects.
A Java record is a compact data class. Jackson can map JSON properties to its components.
public record Item(String name, int quantity) {}This JSON matches the record:
{"name":"widget","quantity":3}The request body must contain valid JSON, and its Content-Type header should identify that format. The Accept header tells the server which response format the client prefers.
Send JSON and parse the response
The following example serializes an Item, sends it in a POST request, and parses a JSON response. The endpoint is illustrative; replace it with your API's URL.
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;
import java.time.Duration;
public class JsonClient {
public record Item(String name, int quantity) {}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
HttpClient client = HttpClient.newHttpClient();
Item item = new Item("widget", 3);
String requestJson = mapper.writeValueAsString(item);
HttpRequest request = HttpRequest.newBuilder(
URI.create("https://api.example.com/items"))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.timeout(Duration.ofSeconds(10))
.POST(HttpRequest.BodyPublishers.ofString(requestJson))
.build();
HttpResponse<String> response = client.send(
request, HttpResponse.BodyHandlers.ofString());
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new IllegalStateException(
"Server returned HTTP " + response.statusCode());
}
Item returnedItem = mapper.readValue(response.body(), Item.class);
System.out.println(returnedItem.name());
System.out.println(returnedItem.quantity());
}
}writeValueAsString serializes a Java value into JSON. readValue deserializes JSON into an Item. Deserialization can fail when a required property is missing, has the wrong type, or contains invalid JSON, so production code should handle Jackson exceptions.
Follow the data flow
Jackson can also parse a response into a tree with readTree when the JSON shape is dynamic. Use a typed record or class when the API contract is stable.
Exercise
Which two headers should normally accompany a JSON POST request, and what does each communicate?
Show answer
Content-Type: application/json describes the request body. Accept: application/json states that the client prefers a JSON response.