Sub topic 12
Sending and parsing JSON with a library
This chapter assumes you can already build a client and a request, send it with send, and check the status code. It also assumes you know basic Java records and checked exceptions.
Where the built-in API stops
HttpClient moves bytes and text. It has no BodyHandler that returns a Java object from JSON, and no BodyPublisher that turns an object into JSON. You choose a JSON library and connect it to the two ends of the exchange. This chapter uses Jackson. Gson and others follow the same pattern.
The pattern has three steps:
- Serialize the object to a JSON
Stringand send it withBodyPublishers.ofString. - Receive the body as a
StringwithBodyHandlers.ofString. - Check the status, then parse the string.
Adding Jackson
Add the databind module. It brings in the core and annotations modules.
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.17.2</version>
</dependency>Use Jackson 2.12 or later if you want to map JSON to Java records.
Two ways to read a response
Tree model
readTree returns a JsonNode. It suits quick scripts or responses where you need one or two fields.
JsonNode json = mapper.readTree(response.body());
String name = json.path("name").asText();get("name") returns null when the field is missing, so a chained call throws a NullPointerException. path("name") returns a missing-node object instead, and asText() on it gives an empty string. Prefer path when a field is optional.
Data binding
readValue maps JSON to a class. A record gives you an immutable type with no boilerplate, and the compiler checks your field access.
Post post = mapper.readValue(response.body(), Post.class);For generic types such as List<Post>, Java erases the type argument at runtime. Pass a TypeReference so Jackson knows the element type:
List<Post> posts = mapper.readValue(body, new TypeReference<List<Post>>() {});If you pass List.class instead, you get a list of LinkedHashMap objects. The code compiles, then fails with a ClassCastException when you read an element.
A complete example
This program fetches a list, then creates a resource with a POST. It uses the public test API at jsonplaceholder.typicode.com.
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
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.time.Duration;
import java.util.List;
public class JsonClient {
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public record Post(Integer userId, Integer id, String title, String body) {}
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final HttpClient CLIENT = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(5))
.build();
static <T> T parse(HttpResponse<String> response, TypeReference<T> type)
throws IOException {
int status = response.statusCode();
if (status < 200 || status >= 300) {
throw new IOException("Unexpected status " + status + ": " + response.body());
}
return MAPPER.readValue(response.body(), type);
}
public static void main(String[] args) throws Exception {
HttpRequest get = HttpRequest.newBuilder(
URI.create("https://jsonplaceholder.typicode.com/posts?userId=1"))
.timeout(Duration.ofSeconds(10))
.header("Accept", "application/json")
.GET()
.build();
HttpResponse<String> listResponse =
CLIENT.send(get, HttpResponse.BodyHandlers.ofString());
List<Post> posts = parse(listResponse, new TypeReference<List<Post>>() {});
System.out.println("Fetched " + posts.size() + " posts");
Post draft = new Post(1, null, "Hello", "Created from Java");
String requestJson = MAPPER.writeValueAsString(draft);
HttpRequest post = HttpRequest.newBuilder(
URI.create("https://jsonplaceholder.typicode.com/posts"))
.timeout(Duration.ofSeconds(10))
.header("Content-Type", "application/json")
.header("Accept", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(requestJson))
.build();
HttpResponse<String> createResponse =
CLIENT.send(post, HttpResponse.BodyHandlers.ofString());
Post created = parse(createResponse, new TypeReference<Post>() {});
System.out.println("Created post with id " + created.id());
}
}Points to notice in this code:
- The
ObjectMapperand theHttpClientarestatic final. Both are thread-safe once configured, and both are costly to create. @JsonInclude(NON_NULL)keeps"id":nullout of the request body. Without it, the server may reject the unexpected field.@JsonIgnoreProperties(ignoreUnknown = true)lets the record ignore fields the API adds later.- The status check comes before parsing. A 404 usually returns an HTML or JSON error body, and parsing it as a
Postwould fail with a confusing message.
Setting the headers yourself
BodyPublishers.ofString does not set Content-Type. Without it, many servers treat the body as plain text or return 415 Unsupported Media Type. Always add Content-Type: application/json on requests with a JSON body. Add Accept: application/json so the server knows what you can read.
Failures that belong to the JSON layer
Jackson's JsonProcessingException extends IOException. Your existing catch (IOException e) therefore also catches malformed JSON and type mismatches. That is convenient, but the message can mislead you into thinking the network failed. If you need to tell them apart, catch JsonProcessingException first:
try {
HttpResponse<String> response =
CLIENT.send(get, HttpResponse.BodyHandlers.ofString());
List<Post> posts = parse(response, new TypeReference<List<Post>>() {});
System.out.println(posts.size());
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
System.err.println("Response was not the JSON we expected: " + e.getOriginalMessage());
} catch (IOException e) {
System.err.println("Network or status failure: " + e.getMessage());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}Choices and edge cases
| Situation | Approach |
|---|---|
| Small to medium response | `ofString`, then `readValue(String, ...)` |
| You want to skip the intermediate `String` | `ofByteArray`, then `readValue(byte[], ...)`. Jackson detects the encoding. |
| Very large JSON array | `ofInputStream` and a Jackson `JsonParser` that reads one element at a time |
| Optional or varying fields | `JsonNode` with `path(...)` |
| Dates and times | Register `jackson-datatype-jsr310` with `mapper.registerModule(new JavaTimeModule())` |
When you use ofInputStream, close the stream, ideally with try-with-resources. An unclosed stream holds the connection.
Common mistakes
- Parsing before checking the status code.
- Forgetting
Content-Type: application/jsonon the request. - Using
List.classinstead of aTypeReference. - Calling
get("field").asText()on an optional field and hitting aNullPointerException. - Making the mapper strict about unknown fields in a client that must survive API additions.
Exercise
A POST with a JSON body returns status 415, although the JSON string is valid. The code uses BodyPublishers.ofString(json) and no headers. What is wrong, and how do you fix it? Separately, why does mapper.readValue(body, List.class) compile but cause trouble later?
Show answer
BodyPublishers.ofString only supplies the bytes. It does not set a content type, so the server cannot tell the body is JSON. Add .header("Content-Type", "application/json") to the request builder. List.class loses the element type through erasure, so Jackson builds a list of LinkedHashMap objects. Reading an element as your own type then throws a ClassCastException. Pass new TypeReference<List<YourType>>() {} instead.