Skip to content
DevTinyTools

Typing

JSON to Java POJOs: primitive or boxed

Java has no way to write “this key was not sent” in an int, and Jackson will not complain: it fills the primitive with 0 and moves on. That single decision, made per field and invisible in the sample, is the difference between a model that reports the document and one that invents values for it.

9 min readTool: JSON to Java

A generated POJO answers 0 where the document said nothing

Java has three ways to declare a number field and JSON has three states for a key, but the two sets do not line up. Generated code usually picks the shortest declaration:

public class Order {
    public long id;
    public String status;
    public double total;
    public int itemCount;
}

Bind an order that omits itemCount and the field reads 0. Bind one that sends "itemCount": null and it also reads 0. Bind one that genuinely sends "itemCount": 0 and it reads 0 again. Three different documents, one value, no exception — and any code downstream that branches on itemCount == 0 now treats “the server forgot the field” as “this order is empty”.

The same document with reference types keeps the distinction. Java calls this the boxed form, and it is the version a model thinking about absence needs:

public class Order {
    public long id;
    public String status;
    public BigDecimal total;
    public Integer itemCount;
}

Nothing about the JSON changed; only the declarations did. What is left is the case Java still cannot express — absent versus null — and that is where the next section starts.

What Jackson actually does, declaration by declaration

The behaviour is decided by Jackson’s defaults, not by the field name, and the defaults are quiet. FAIL_ON_NULL_FOR_PRIMITIVES is off, so a null arriving at a primitive is written as 0 with no warning. The table below is the whole decision surface:

Jackson behaviour for primitive, boxed and Optional fields
DeclarationKey absentKey is nullVerdict
double total;0.0 — indistinguishable from a real zero0.0 — silently, because FAIL_ON_NULL_FOR_PRIMITIVES is offOnly safe when the field is always sent and never null.
Double total;nullnullSeparates a real zero from nothing, but not null from absent.
Optional<Double> total;null — the field is never assignedOptional.empty()Works only with jackson-datatype-jdk8 registered, and it still leaves absent as null.
double total; + FAIL_ON_NULL_FOR_PRIMITIVES0.0JsonMappingExceptionTurns one of the two silent cases into an error. Absent stays silent.

Read the second column, not the third. Everyone worries about null because it is visible in the payload, but an absent key is the common case with optional fields and no declaration in the table recovers it: Jackson simply never calls the setter, so the field keeps whatever the constructor left there. A reference type gives you null for both, which is honest about the fact that you cannot tell them apart — and is why the Go guide arrives at the same conclusion from a different language.

If you genuinely need to know whether a key was present, the only reliable mechanism is to observe the setter — a flag set inside it, or @JsonAnySetter with a map — because by the time the field is assigned, the information is gone. Everything else is inference from null.

Records are shorter, and stricter about names

Java 16 records are the right shape for a read-only API model: one line per component, plus equals, hashCode and toString generated for you, which a plain POJO only gets through Lombok or by hand.

public record Order(
        long id,
        String status,
        BigDecimal total,
        Integer itemCount) {
}

The catch is invisible at compile time. Jackson binds a record through its canonical constructor, and to do that it needs the parameter names — but the JVM does not keep them unless you compile with -parameters. Without that flag every component reads as arg0, arg1 and binding fails with an error listing unknown properties. Annotating each component works regardless of compiler flags, which is why generated records carry the annotations even when the names already match:

public record Order(
        @JsonProperty("id") long id,
        @JsonProperty("status") String status,
        @JsonProperty("total") BigDecimal total,
        @JsonProperty("item_count") Integer itemCount) {
}

Add the flag in maven-compiler-plugin or javac -parameters and you can drop the annotations for fields whose names match exactly. Keep them for anything that was renamed, or the record stops binding the moment someone changes the JSON key.

Records also cannot extend a class and cannot have mutable fields, which is fine for a response model and wrong for a form-backing bean that a UI framework populates property by property. That is the one case where the plain POJO is still the right answer.

Why every nested class must be static

A non-static inner class holds an implicit reference to its enclosing instance, and the compiler makes that reference a parameter of its constructor. Jackson asks the class for a no-argument constructor, does not find one, and throws an InvalidDefinitionException mentioning that no suitable constructor exists.

public class Order {
    public long id;
    public Customer customer;

    // static: Jackson can construct this on its own
    public static class Customer {
        public String email;
    }
}

The static keyword removes the hidden parameter without changing how the class is used, and keeps the nesting as pure organisation. It is also why a generator that emits Java classes places them inside the parent as public static class instead of as separate top-level types: Java allows exactly one public top-level class per file, so nesting is the only way to keep a small model in one file that compiles.

double is a measurement type, not a money type

A JSON number does not carry units, and no amount of sampling tells a generator whether 19.50 is a price, a weight or a ratio. It therefore emits double, which is the right default for measurements and the wrong one for money: binary floating point cannot represent 0.1 exactly, so sums drift and comparisons fail.

// wrong for money: 0.1 + 0.2 != 0.3
public double total;

// right for money: exact decimal, no binary rounding
public BigDecimal total;

// and if the JSON sends a string, say so:
@JsonFormat(shape = JsonFormat.Shape.STRING)
public BigDecimal total;

Two follow-ups belong in the same pass over the generated file. First, if the payload sends prices as strings (common in payment APIs), tell Jackson with @JsonFormat(shape = STRING) — without it a string arriving at a BigDecimal field is accepted only because Jackson coerces by default, and that coercion is easy to lose when someone enables strict mode. Second, pick the scale explicitly: BigDecimal keeps the scale it parsed (19.50 stays 19.50, with two decimal places), which matters when you send the value back to an accounting system that compares by scale.

Integers are the easier half. A long holds a 19-digit ID exactly, and Jackson parses the literal straight into it without a double detour. The rounding you may have seen elsewhere happened before the payload reached Java — see why JSON numbers lose precision for the JavaScript leg of that journey.

Round-trip the payload before you trust the model

A round trip catches almost every binding bug at once: bind the real payload, write it back out, and compare as JSON trees. A field that disappears points at a name Jackson never matched; a value that changed points at a numeric type; a field that turned into 0 points at a primitive.

class OrderTest {
    private final ObjectMapper mapper = new ObjectMapper()
            .registerModule(new JavaTimeModule());

    @Test
    void roundTripsThePayload() throws Exception {
        String raw = "{\"id\":84126,\"total\":\"19.50\",\"coupon_code\":null}";

        Order order = mapper.readValue(raw, Order.class);
        assertNull(order.couponCode);

        JsonNode before = mapper.readTree(raw);
        JsonNode after = mapper.readTree(mapper.writeValueAsString(order));

        // LENIENT: ignore extra fields the POJO does not model
        JSONAssert.assertEquals(before, after, JSONCompareMode.LENIENT);
    }
}

Compare trees rather than strings — key order and whitespace are free to differ — and run it leniently so fields the POJO deliberately omits do not fail the test. Keep one captured response per endpoint as a fixture, and the suite becomes a contract that a regenerated model has to satisfy.

  • Start from a real response. Hand-written samples contain exactly the fields you remembered, which is why they never catch the missing one.
  • Assert the null case explicitly. A second fixture with coupon_code: null is what proves the field is boxed rather than primitive.
  • Regenerate, then re-run. The point of the test is to fail when the API changes shape, not to be satisfied once in review.

Frequently asked questions

Why does the generator use Integer instead of int?
Because int has no way to say nothing. A primitive int field that no key was provided for holds 0, which is a legal value — so a caller reading itemCount cannot tell a real zero from a field the server never sent. Integer is a reference, so an absent or null key leaves it null and the difference survives. The cost is one null check and a boxed object per field, which is nothing next to a wrong total.
Does FAIL_ON_NULL_FOR_PRIMITIVES fix the primitive problem?
Half of it. Enabling that DeserializationFeature makes an explicit null throw instead of becoming 0, which is a real improvement. It cannot help with an absent key, because Jackson never sees the key at all — there is nothing to fail on. If distinguishing absent from null matters, use a reference type or Optional, not a feature flag.
Why are the nested classes static?
An inner class that is not static carries a hidden reference to an enclosing instance, so its constructor takes an extra parameter Jackson cannot supply. Deserialisation fails with a message about no suitable constructor. The static keyword removes that parameter and gives Jackson a plain class it can instantiate, while keeping the nesting purely organisational.
Should I use a record instead of a class?
If the model is read-only, yes — a record gives immutability plus equals, hashCode and toString for free, which a plain POJO only gets through Lombok. Jackson supports records from 2.12, but parameter names are only visible at runtime if you compile with -parameters; without that flag every parameter looks like arg0 and binding fails, unless you annotate each component with @JsonProperty.
Why does the generator emit BigDecimal for some fields?
It does not — this is the one decision a sample cannot make. A JSON number 19.50 could be a price, a weight or a ratio, and all three arrive as the same token. The generator emits double, which is right for measurements and wrong for money, because 0.1 + 0.2 is not 0.3 in binary floating point. Change the money fields to BigDecimal yourself; the guide you are reading explains where the boundary is.
Can a long hold a 19-digit ID safely?
Java's long is 64-bit and exact, so 9021073482910473821 fits with room to spare — as long as Jackson parses it directly into a long. The precision is lost elsewhere: if an intermediate JavaScript service parsed the JSON first, the value was already rounded to a double. Java is the safe endpoint, not a safe transport.
How do dates come through?
As strings, unless you register JavaTimeModule and declare LocalDate, LocalDateTime, Instant or OffsetDateTime. With the module registered, ISO 8601 binds automatically. Use Instant for timestamps with a Z suffix and OffsetDateTime when the original offset must survive, because Instant normalises everything to UTC.
What is @JsonProperty actually doing?
It replaces the property name Jackson derives from the field or getter with the exact string you give it. The generator emits it whenever the Java name differs from the JSON key — snake_case fields, kebab-case keys, or names that had to be renamed because a digit or a reserved word made the original illegal as an identifier.