JSON
JSON is a text format for objects, arrays, and scalars. In Java you map it to records and classes with Jackson, Gson, or Jakarta JSON Binding. HTTP APIs almost always speak JSON.
Detailed Explanation
{"name":"Ada","age":36} is an object. Arrays, strings, numbers, booleans, and null are the other values. There are no dates or comments in the spec. Dates become strings (ISO-8601) or numbers. Java Optional, LocalDateTime, and enums need a policy.
Jackson (ObjectMapper) is the Spring default. readValue parses. writeValueAsString writes. Records work as DTOs. @JsonProperty renames fields. @JsonIgnore hides them. Unknown properties fail or are ignored depending on FAIL_ON_UNKNOWN_PROPERTIES. Snake_case vs camelCase is a config (PropertyNamingStrategies).
Never build JSON with string concatenation when user data is involved; you will break escaping and open injection holes in HTML contexts. Use a mapper. For JSON inside a relational column, still validate the shape.
You reach for a mapper at the HTTP boundary. You keep domain types free of Jackson annotations when you can, and map to DTOs. You reach for JSON-B on Jakarta stacks. You do not parse JSON with regex.
The cost of mapping entities is lazy loads and password fields in the dump. The cost of Map<String, Object> everywhere is no schema. The cost of a shared ObjectMapper you mutate is a race; configure once, reuse. The cost of numbers as IEEE doubles is money bugs; use BigDecimal or integer minor units.
application/json charset is UTF-8. Write it on the response. Pretty-print in logs, not on the hot path.
Treat the mapper as infrastructure: one configured instance, tested with a golden string for the types you ship. If a field is added, decide whether old clients may ignore it. If a field is removed, that is a breaking change. Version the DTO or add the field as optional. JSON looks casual. On the wire it is your public API, the same as a Java interface you cannot take back.
Code Examples
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonRound {
record User(String name, int age) {}
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(new User("Ada", 36));
User user = mapper.readValue(json, User.class);
System.out.println(json.contains("Ada")); // prints: true
System.out.println(user.age()); // prints: 36
}
}public class Escape {
public static void main(String[] args) {
String unsafe = "Ada \"the\"";
// Do not: "{ \"name\": \"" + unsafe + "\" }"
System.out.println(unsafe.length() > 0); // prints: true
}
}Common Gotchas
Concatenating JSON with user strings breaks quotes and can inject
use a mapper.
`double` for money is wrong
use integer minor units or `BigDecimal` with a string.
Unknown properties can fail deserialization
decide and configure the mapper once.
Serializing JPA entities leaks fields and triggers lazy loads
Serializing JPA entities leaks fields and triggers lazy loads