A Spring Boot service, a batch job or an Android app receives JSON from another system, and the Java code needs typed objects to work with. Jackson is the library most Java projects use for this, and it is powerful, but its defaults surprise people: a single unexpected field can throw an exception, and a missing number silently becomes zero.
This guide walks through how Jackson binds JSON to Java classes, when a record is a better fit than a classic POJO, and how to generate a correct first draft of your model from a sample response. The last section lists the edits that a generated model almost always needs.
How Jackson binds JSON to a Java class
Jackson's ObjectMapper reads a JSON document and creates an instance of the class you ask for. It finds properties in two ways:
- Through getters and setters (POJOs). A setter
setOrderId(String)makes a property calledorderId. Jackson creates the object with the no-argument constructor, then calls the setters. - Through a constructor (records). From Jackson 2.12 onward, Java records are supported: the record's components become properties and Jackson calls the canonical constructor.
A few defaults matter in daily work:
| Situation | Jackson's default behaviour |
|---|---|
| JSON has a key the class does not know | Throws UnrecognizedPropertyException |
| JSON lacks a key the class has | Leaves the field at its default (null, 0, false) |
JSON has null for an int or long field |
Uses 0 rather than failing |
| JSON key uses snake_case, field uses camelCase | No match unless you add @JsonProperty or a naming strategy |
The first row is the most common source of production errors. APIs add fields over time, and a strict mapper turns a harmless addition into a failed request. The usual fix is @JsonIgnoreProperties(ignoreUnknown = true) on the class, or disabling DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES on the mapper.
POJO or record?
A POJO with getters and setters works on every Java version, suits frameworks that expect mutable beans (JPA entities, older form binders), and lets you change values after reading them. A record (Java 16 and later) needs a fraction of the code, is immutable, and has equals, hashCode and toString built in. For data transfer objects that you read and pass along, records are usually the cleaner choice.
One trade-off: primitive types (long, double, boolean) cannot hold null. If the JSON can omit a value or send null, use the boxed type (Long, Double, Boolean) so you can tell "zero" apart from "not provided".
Generate the Java model from a JSON sample
The JSON to Java Class tool writes the classes for you in the browser; the sample is not uploaded.
- Open JSON to Java Class and paste a response into JSON sample, use Open file, or click Load sample.
- Set Root type name, for example
Shipment. - Add a Package (optional) such as
com.example.logistics.modelso the first line is apackagestatement. - Choose Declare as: POJO with getters/setters or record (Java 16+).
- Leave Jackson annotations on to get
@JsonIgnoreProperties(ignoreUnknown = true)on every type and@JsonProperty("...")wherever a JSON key is not a valid camelCase Java name (for exampletracking_codebecomes the fieldtrackingCodewith the original key in the annotation). - Copy the Java output or Download it as a
.javafile.
The generator names nested types from their keys (an items array becomes List<Item>), merges identical shapes into one type, and uses boxed types where the sample shows null or where a key is missing from some objects. Only the root type is declared public, and the output ends with a comment telling you to save it under the root type's file name; the other types are package-private so the single file compiles. You can move them into their own files later.
Reading JSON with ObjectMapper
Add com.fasterxml.jackson.core:jackson-databind to your build (Spring Boot includes it already). Then:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
ObjectMapper mapper = new ObjectMapper();
// A single object
Shipment shipment = mapper.readValue(Files.readString(Path.of("shipment.json")), Shipment.class);
// A top-level JSON array
List<Shipment> all = mapper.readValue(json, new TypeReference<List<Shipment>>() {});
ObjectMapper is thread-safe once configured and relatively expensive to create, so build it once and share it (in Spring, inject the one the framework provides).
If you would rather not annotate every snake_case field, set a naming strategy on the mapper:
mapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
Other ways to create Java classes from JSON
- Write the class yourself. For a small payload, typing a record by hand takes a minute and you pick exact types from the start.
- IDE plugins. IntelliJ IDEA and other IDEs have plugins that generate POJOs from pasted JSON. They are convenient if you already work there, though the output style varies by plugin.
- Schema-driven generators. When the provider publishes an OpenAPI or JSON Schema contract, generating from that contract is more reliable than any sample, because it states which fields are required and which types are allowed. The JSON Schema Generator can draft a schema from samples if you want a contract to review and share.
- Tree model. For a quick script,
mapper.readTree(json)returns aJsonNodeyou can query without classes.
Fixing the generated model
Replace Object fields
When a key is null in every sample, the tool cannot see its real type and writes Object. Look up the field in the API documentation or paste a sample where it is filled, then change it to String, Long or a nested type.
Use proper date and money types
Timestamps are generated as String. Change them to java.time.OffsetDateTime, Instant or LocalDate, and register the Java time module: mapper.findAndRegisterModules() picks up jackson-datatype-jsr310 if it is on the classpath. For amounts, prefer BigDecimal over double, which cannot store most decimal fractions exactly.
Check boolean names
A JSON key such as isActive produces a field isActive and a getter isIsActive(). Jackson maps that correctly to isActive, but the name reads oddly. If you rename the field to active, add @JsonProperty("isActive") so the JSON key still matches.
Check numbers that happen to be whole
A price of 12 in your sample produces long, even if other responses contain 12.50. Paste several samples as an array, or fix the type by hand.
If the sample will not parse, find the syntax error with the JSON Validator first. For the same payload in other languages, JSON to C# Class and JSON to Go Struct follow the same approach.
Frequently asked questions
Why does Jackson throw UnrecognizedPropertyException?
The JSON contains a field your class does not declare, and Jackson fails on unknown properties by default. Add @JsonIgnoreProperties(ignoreUnknown = true) to the class or disable FAIL_ON_UNKNOWN_PROPERTIES on the ObjectMapper.
Does Jackson support Java records?
Yes, since Jackson 2.12. Record components are treated as properties and the canonical constructor is used to create the object, so no setters or default constructor are needed.
Should I use long or Long for JSON numbers?
Use Long when the value can be missing or null, so you can distinguish "no value" from zero. Use long only when the API always sends the field.
How do I map snake_case JSON keys to camelCase fields?
Annotate individual fields with @JsonProperty("snake_key"), or set PropertyNamingStrategies.SNAKE_CASE on the mapper to convert all names at once.
Can I use the generated classes with Gson instead of Jackson?
Switch off Jackson annotations to get plain classes. Gson reads fields directly, so a POJO works; for keys that differ from field names, use Gson's own @SerializedName annotation.