Reading request bodies and writing JSON responses
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A phone app sends a new product, and the server receives only bytes. A typo such as "nmae" must not save a product with no name. Jackson and a few firm rules turn the bytes into records and back.
Reading the request body stream into a record with Jackson
readValue (mapper.readValue(stream, Type.class)) reads JSON bytes from a stream and builds a Java object, matching JSON names to record components. For a request, the stream is exchange.getRequestBody().
Example 1 reads a request body into a record. Example 2 shows why Jackson's default settings are too lenient for a server.
Example 1 · readValue: request bytes into a record
Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.InputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import tools.jackson.databind.json.JsonMapper;
/** The request body of POST /api/v1/categories. Boxed Integer, so a missing parentId is null. */record NewCategory(String name, Integer parentId) {}
public class ReadBodyDemo { private static final JsonMapper JSON = JsonMapper.builder().build(); // one mapper for the server
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/categories", exchange -> { try (exchange; InputStream in = exchange.getRequestBody()) { NewCategory input = JSON.readValue(in, NewCategory.class); // bytes -> record System.out.println(" server read: " + input); exchange.sendResponseHeaders(204, -1); } }); server.start();
URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/categories"); HttpClient client = HttpClient.newHttpClient(); try { for (String body : new String[] {"{\"name\":\"Stationery\",\"parentId\":null}", "{\"name\":\"Tablets\",\"parentId\":1}", "{\"name\":\"Toys\"}"}) { System.out.println("POST " + body); HttpRequest request = HttpRequest.newBuilder(uri) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(body)) .build(); System.out.println(" status " + client.send(request, HttpResponse.BodyHandlers.discarding()).statusCode()); } } finally { server.stop(0); } }}POST {"name":"Stationery","parentId":null}
server read: NewCategory[name=Stationery, parentId=null]
status 204
POST {"name":"Tablets","parentId":1}
server read: NewCategory[name=Tablets, parentId=1]
status 204
POST {"name":"Toys"}
server read: NewCategory[name=Toys, parentId=null]
status 204What this code does
JSON.readValue(in, NewCategory.class)reads the body stream and fills the record by name.parentIdis anInteger, sonulland a missing key both arrive asnull.try (exchange; InputStream in = ...)closes both on every path. The handler answers204, because this demo saves nothing.
Example 2 · Mistake: Jackson 3 defaults are too lenient for a server
Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)
import java.math.BigDecimal;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.MapperFeature;import tools.jackson.databind.json.JsonMapper;
record NewProduct(String sku, String name, Integer categoryId, BigDecimal price, Integer stock) {}
public class StrictMapperDemo {
static void read(String label, JsonMapper mapper, String json) { try { System.out.println(label + mapper.readValue(json, NewProduct.class)); } catch (JacksonException e) { System.out.println(label + e.getClass().getSimpleName()); } }
public static void main(String[] args) { JsonMapper lenient = JsonMapper.builder().build(); JsonMapper strict = JsonMapper.builder() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) .build();
String[] bodies = { "{\"sku\":\"BK-DSA\",\"nmae\":\"DSA Made Easy\",\"categoryId\":5,\"price\":549.00,\"stock\":10}", "{\"sku\":\"BK-DSA\",\"name\":\"DSA Made Easy\",\"categoryId\":5,\"price\":549.00,\"stock\":5.5}", "{\"sku\":\"BK-DSA\",\"name\":\"DSA Made Easy\",\"categoryId\":5,\"price\":549.00,\"stock\":\"30\"}", "{\"sku\":\"BK-DSA\",\"name\":\"DSA Made Easy\",\"categoryId\":5,\"price\":549.00,\"stock\":30}"}; for (String body : bodies) { System.out.println(body); read(" lenient: ", lenient, body); read(" strict: ", strict, body); } }}{"sku":"BK-DSA","nmae":"DSA Made Easy","categoryId":5,"price":549.00,"stock":10}
lenient: NewProduct[sku=BK-DSA, name=null, categoryId=5, price=549.00, stock=10]
strict: UnrecognizedPropertyException
{"sku":"BK-DSA","name":"DSA Made Easy","categoryId":5,"price":549.00,"stock":5.5}
lenient: NewProduct[sku=BK-DSA, name=DSA Made Easy, categoryId=5, price=549.00, stock=5]
strict: InvalidFormatException
{"sku":"BK-DSA","name":"DSA Made Easy","categoryId":5,"price":549.00,"stock":"30"}
lenient: NewProduct[sku=BK-DSA, name=DSA Made Easy, categoryId=5, price=549.00, stock=30]
strict: MismatchedInputException
{"sku":"BK-DSA","name":"DSA Made Easy","categoryId":5,"price":549.00,"stock":30}
lenient: NewProduct[sku=BK-DSA, name=DSA Made Easy, categoryId=5, price=549.00, stock=30]
strict: NewProduct[sku=BK-DSA, name=DSA Made Easy, categoryId=5, price=549.00, stock=30]What this code does
- With the defaults, the typo
nmaeis ignored andnamebecomesnull;5.5silently becomes5; the text"30"becomes the number 30. Each is a client bug that the server hides. - The strict mapper turns each one into an exception:
UnrecognizedPropertyException,InvalidFormatExceptionandMismatchedInputException. A correct body reads the same with both mappers.
Use one shared JsonMapper for the whole server: it is thread-safe and costly to build. Give request records boxed types (Integer, BigDecimal, Boolean), so a field the client left out arrives as null and you can report it, instead of a silent 0 or false.
Jackson 3 is forgiving by default. It ignores unknown fields, so a typo like "nmae" leaves name as null; it turns 5.5 into 5 for an int; and it accepts the text "30" for a number. Each of these hides a client bug, so a server switches them off, as the strict mapper of Example 2 does.
Checking Content-Type and returning 415
415 Unsupported Media Type is the answer when the Content-Type request header is not application/json (any letter case, with or without parameters such as ; charset=UTF-8) or is missing. The server checks it before reading the body.
Example 3 accepts a JSON body and rejects text/plain and a missing header with 415.
Example 3 · Content-Type check: 201 or 415
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.nio.charset.StandardCharsets;import java.util.Locale;
public class ContentTypeCheckDemo {
/** application/json, with or without parameters such as ; charset=UTF-8, in any letter case. */ static boolean isJson(String contentType) { return contentType != null && contentType.toLowerCase(Locale.ROOT).startsWith("application/json"); }
static void create(HttpExchange exchange) throws IOException { try (exchange) { String type = exchange.getRequestHeaders().getFirst("Content-Type"); if (!isJson(type)) { send(exchange, 415, "Send the body as application/json"); return; // the body is never parsed } exchange.getRequestBody().readAllBytes(); send(exchange, 201, "created"); } }
static void send(HttpExchange exchange, int status, String text) throws IOException { byte[] body = text.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/categories", ContentTypeCheckDemo::create); server.start(); URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/categories"); HttpClient client = HttpClient.newHttpClient(); String[] types = {"application/json", "application/json; charset=UTF-8", "Application/JSON", "text/plain", null}; try { for (String type : types) { HttpRequest.Builder builder = HttpRequest.newBuilder(uri) .POST(HttpRequest.BodyPublishers.ofString("{\"name\":\"Stationery\"}")); if (type != null) { builder.header("Content-Type", type); } HttpResponse<String> r = client.send(builder.build(), HttpResponse.BodyHandlers.ofString()); System.out.printf("%-32s -> %d %s%n", type == null ? "(no Content-Type)" : type, r.statusCode(), r.body()); } } finally { server.stop(0); } }}application/json -> 201 created application/json; charset=UTF-8 -> 201 created Application/JSON -> 201 created text/plain -> 415 Send the body as application/json (no Content-Type) -> 415 Send the body as application/json
What this code does
isJsonacceptsapplication/jsonwith a charset parameter and in any letter case, because media types are case-insensitive.text/plainand a missing header both get415before the body is read. The client learns what to fix: the header, not the JSON.
A form post (name=Toys) or plain text would otherwise get a vague "not valid JSON" error. 415 tells the client exactly what to change, and it stops the server from guessing.
Media types are case-insensitive, so compare in lower case, and use startsWith, not equals, because clients often add ; charset=utf-8.
Predict the output
Is the body read?
Pick what the server does with each request.
Round 1 of 3
What does the server do?
Writing JSON with the right Content-Type, charset and length
writeValueAsBytes (mapper.writeValueAsBytes(value)) turns a record into JSON bytes in UTF-8. Send them with Content-Type: application/json and pass bytes.length to sendResponseHeaders.
Example 4 writes a product as JSON and shows the byte length that is sent.
Example 4 · Writing a record as JSON with the byte length
Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)
import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.math.BigDecimal;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import tools.jackson.databind.json.JsonMapper;
/** A product as the API sends it. Field names become the JSON names. */record ProductResponse(int id, String sku, String name, int categoryId, String categoryName, BigDecimal price, int stock, boolean isActive) {}
public class WriteJsonDemo { private static final JsonMapper JSON = JsonMapper.builder().build();
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/products/12", exchange -> { ProductResponse kurta = new ProductResponse(12, "FSH-KURTA", "Cotton Kurta – Indigo", 6, "Fashion", new BigDecimal("899.00"), 35, true); byte[] body = JSON.writeValueAsBytes(kurta); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(200, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }); server.start(); URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/products/12"); try { HttpResponse<String> r = HttpClient.newHttpClient() .send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString()); System.out.println(r.statusCode() + " " + r.headers().firstValue("Content-Type").orElse("?") + ", Content-Length " + r.headers().firstValue("Content-Length").orElse("?") + ", characters " + r.body().length()); System.out.println(r.body().replace("–", "-")); } finally { server.stop(0); } }}200 application/json, Content-Length 142, characters 140
{"id":12,"sku":"FSH-KURTA","name":"Cotton Kurta - Indigo","categoryId":6,"categoryName":"Fashion","price":899.00,"stock":35,"isActive":true}What this code does
writeValueAsBytesgives UTF-8 bytes. The en dash in the name takes 3 bytes, soContent-Lengthis 142 while the text has 140 characters: passingbody.lengthis what makes it correct.- The record names become the JSON names (
categoryName,isActive) and theBigDecimalprice keeps899.00. The demo replaces the dash only when printing, to keep the console plain.
The length must be the byte count. A product name with an en dash (–) or a ₹ sign has more bytes than characters, and String.length() would break the response, as in the first lesson of this module. Writing bytes directly avoids the mistake, because there is no String to measure. JSON over HTTP is always UTF-8, so application/json needs no charset parameter.
Records give exact field names (isActive, categoryName), and BigDecimal prices keep their two decimals (899.00). Never build response JSON with +: one quote in a product name breaks it.
Find the bug
Find the response bug
Click the line that is wrong.
Some product names make the client misread the response. Which line?
Round 1 of 2Query parameters for filters and paging
A query record is a small record such as ProductQuery that holds the optional query parameters of a list request: filters like categoryId=2 and paging with page (from 0) and size (default 20, at most 100).
Example 5 reads filters and paging from a query string and reports every bad value at once.
Example 5 · Filters and paging from the query, every error at once
import java.math.BigDecimal;import java.net.URLDecoder;import java.nio.charset.StandardCharsets;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
/** What a product list asks for: filters plus a page. page counts from 0. */record ProductQuery(String q, Integer categoryId, BigDecimal maxPrice, int page, int size) {}
public class ListQueryDemo {
static Map<String, String> parse(String rawQuery) { Map<String, String> params = new LinkedHashMap<>(); if (rawQuery != null) { for (String pair : rawQuery.split("&")) { String[] parts = pair.split("=", 2); params.putIfAbsent(URLDecoder.decode(parts[0], StandardCharsets.UTF_8), parts.length > 1 ? URLDecoder.decode(parts[1], StandardCharsets.UTF_8).trim() : ""); } } return params; }
/** Reads every parameter, collects every problem, and only then decides: a query or a 400. */ static Object read(String rawQuery) { Map<String, String> p = parse(rawQuery); List<String> errors = new ArrayList<>(); Integer categoryId = null; BigDecimal maxPrice = null; int page = 0; int size = 20; try { if (!p.getOrDefault("categoryId", "").isEmpty()) { categoryId = Integer.valueOf(p.get("categoryId")); } } catch (NumberFormatException e) { errors.add("categoryId must be a whole number"); } try { if (!p.getOrDefault("maxPrice", "").isEmpty()) { maxPrice = new BigDecimal(p.get("maxPrice")); } } catch (NumberFormatException e) { errors.add("maxPrice must be a number"); } try { page = Integer.parseInt(p.getOrDefault("page", "0")); if (page < 0) { errors.add("page must be 0 or more"); } } catch (NumberFormatException e) { errors.add("page must be a whole number"); } try { size = Integer.parseInt(p.getOrDefault("size", "20")); if (size < 1 || size > 100) { errors.add("size must be between 1 and 100"); // never silently clamp to 100 } } catch (NumberFormatException e) { errors.add("size must be a whole number"); } if (!errors.isEmpty()) { return "400 " + errors; } String q = p.getOrDefault("q", ""); return new ProductQuery(q.isEmpty() ? null : q, categoryId, maxPrice, page, size); }
public static void main(String[] args) { String[] queries = {null, "q=redmi+note&maxPrice=20000", "categoryId=2&page=1&size=2", "size=500&page=-1", "categoryId=two&maxPrice=cheap", "utm_source=whatsapp"}; for (String query : queries) { System.out.println("?" + query + "\n -> " + read(query)); } }}?null -> ProductQuery[q=null, categoryId=null, maxPrice=null, page=0, size=20] ?q=redmi+note&maxPrice=20000 -> ProductQuery[q=redmi note, categoryId=null, maxPrice=20000, page=0, size=20] ?categoryId=2&page=1&size=2 -> ProductQuery[q=null, categoryId=2, maxPrice=null, page=1, size=2] ?size=500&page=-1 -> 400 [page must be 0 or more, size must be between 1 and 100] ?categoryId=two&maxPrice=cheap -> 400 [categoryId must be a whole number, maxPrice must be a number] ?utm_source=whatsapp -> ProductQuery[q=null, categoryId=null, maxPrice=null, page=0, size=20]
What this code does
- No query gives the defaults
page=0, size=20.redmi+notedecodes toredmi note, and an unknown parameter such asutm_sourcechanges nothing. - Bad values do not stop at the first problem:
size=500&page=-1reports both, so the client fixes everything in one round.sizeis never clamped to 100 behind the client's back.
Treat each parameter as untrusted text. Parse numbers with Integer.valueOf or new BigDecimal inside a try, check the ranges, and collect every problem before answering, so the client fixes all of them in one go. A bad value gets 400; a value out of range is never silently changed (size=500 is an error, not 100). Unknown parameters such as utm_source are ignored.
An allow-list protects the sort parameter: only id, name, price or stock may reach the SQL, never the client's own text.
A small helper for reading and writing JSON
A JSON helper (here JsonIo) puts every body rule in one class: read(exchange, Type.class) checks Content-Type (415), limits the size and parses strictly (400); write(exchange, status, value) sets the type and byte length and closes the stream.
Example 6 builds JsonIo. After that, a handler needs three lines: read the record, call the logic, write the result.
Example 6 · JsonIo: one helper for 415, 400 and JSON output
Runs in: a Maven project with Jackson 3 (tools.jackson.core:jackson-databind 3.1.5)
import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpServer;import java.io.IOException;import java.io.OutputStream;import java.net.InetSocketAddress;import java.net.URI;import java.net.http.HttpClient;import java.net.http.HttpRequest;import java.net.http.HttpResponse;import java.util.List;import java.util.Locale;import java.util.concurrent.CopyOnWriteArrayList;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.MapperFeature;import tools.jackson.databind.json.JsonMapper;
/** Thrown by JsonIo.read when the request cannot become a record; the handler turns it into a response. */class BadRequestException extends RuntimeException { final int status;
BadRequestException(int status, String message) { super(message); this.status = status; }}
/** Every JSON read and write of the server goes through here: one strict mapper, one set of rules. */final class JsonIo { static final int MAX_BODY_BYTES = 64 * 1024; private static final JsonMapper MAPPER = JsonMapper.builder() .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES) .disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT) .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) .build();
private JsonIo() { }
/** Content-Type check (415), size limit and parse (400), in that order. */ static <T> T read(HttpExchange exchange, Class<T> type) throws IOException { String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType == null || !contentType.toLowerCase(Locale.ROOT).startsWith("application/json")) { throw new BadRequestException(415, "Send the body as application/json"); } byte[] bytes = exchange.getRequestBody().readNBytes(MAX_BODY_BYTES + 1); if (bytes.length > MAX_BODY_BYTES) { throw new BadRequestException(400, "The body is larger than 64 KB"); } try { T value = MAPPER.readValue(bytes, type); if (value == null) { throw new BadRequestException(400, "The body must be a JSON object"); // the text "null" } return value; } catch (JacksonException e) { throw new BadRequestException(400, "The body is not valid JSON for this request"); } }
/** Writes any object (record, list, map) as JSON with the right type and byte length. */ static void write(HttpExchange exchange, int status, Object value) throws IOException { byte[] body = MAPPER.writeValueAsBytes(value); exchange.getResponseHeaders().set("Content-Type", "application/json"); exchange.sendResponseHeaders(status, body.length); try (OutputStream out = exchange.getResponseBody()) { out.write(body); } }}
record NewCategory(String name, Integer parentId) {}
record ErrorBody(int status, String detail) {}
record Category(int id, String name, Integer parentId) {}
public class JsonHelperDemo { static final List<Category> CATEGORIES = new CopyOnWriteArrayList<>(List.of(new Category(1, "Electronics", null)));
static void categories(HttpExchange exchange) throws IOException { try (exchange) { if (exchange.getRequestMethod().equals("GET")) { JsonIo.write(exchange, 200, CATEGORIES); return; } try { NewCategory input = JsonIo.read(exchange, NewCategory.class); Category saved = new Category(CATEGORIES.size() + 1, input.name(), input.parentId()); CATEGORIES.add(saved); JsonIo.write(exchange, 201, saved); } catch (BadRequestException e) { JsonIo.write(exchange, e.status, new ErrorBody(e.status, e.getMessage())); } } }
public static void main(String[] args) throws IOException, InterruptedException { HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); server.createContext("/api/v1/categories", JsonHelperDemo::categories); server.start(); URI uri = URI.create("http://127.0.0.1:" + server.getAddress().getPort() + "/api/v1/categories"); HttpClient client = HttpClient.newHttpClient(); String[][] posts = {{"application/json", "{\"name\":\"Stationery\",\"parentId\":null}"}, {"application/json", "{\"name\":\"Stationery\","}, {"application/json", "{\"id\":9,\"name\":\"Toys\"}"}, {"application/json", "{\"name\":\"Toys\",\"parentId\":\"one\"}"}, {"text/plain", "name=Toys"}}; try { for (String[] post : posts) { HttpRequest request = HttpRequest.newBuilder(uri).header("Content-Type", post[0]) .POST(HttpRequest.BodyPublishers.ofString(post[1])).build(); HttpResponse<String> r = client.send(request, HttpResponse.BodyHandlers.ofString()); System.out.println("POST " + post[1] + "\n -> " + r.statusCode() + " " + r.body()); } System.out.println("GET -> " + client.send(HttpRequest.newBuilder(uri).build(), HttpResponse.BodyHandlers.ofString()).body()); } finally { server.stop(0); } }}POST {"name":"Stationery","parentId":null}
-> 201 {"id":2,"name":"Stationery","parentId":null}
POST {"name":"Stationery",
-> 400 {"status":400,"detail":"The body is not valid JSON for this request"}
POST {"id":9,"name":"Toys"}
-> 400 {"status":400,"detail":"The body is not valid JSON for this request"}
POST {"name":"Toys","parentId":"one"}
-> 400 {"status":400,"detail":"The body is not valid JSON for this request"}
POST name=Toys
-> 415 {"status":415,"detail":"Send the body as application/json"}
GET -> [{"id":1,"name":"Electronics","parentId":null},{"id":2,"name":"Stationery","parentId":null}]What this code does
JsonIo.readchecks the type, reads at most 64 KB plus one byte and parses strictly; every problem becomes aBadRequestExceptionwith a status.JsonIo.writesets the type and byte length for any object.- Broken JSON, an
idthe client must not send, and text where a number belongs all get400;text/plaingets415. The handler itself stays short: read, save, write. - The error body here is a simple record. The next lesson replaces it with the Problem Details format of the ShopLite contract, with one
typeper kind of error.
Without a helper, every handler repeats the same ten lines, and one of them forgets the 415 check or the length rule.
The size limit matters: readNBytes(limit + 1) never reads more than the limit plus one byte, so a 1 GB upload cannot fill the server's memory. ShopLite uses 64 KB, far more than any product or order needs.
Next step
Check your understanding
11 quick questions