Skip to lesson

Handling unknown or missing fields

A client sends a typo, leaves a field out or sends text where a number belongs. Your API must decide what to do and answer with a clear message, not a stack trace.

Unknown properties: failing versus ignoring, per class and per mapper

Unknown property is a key in the JSON that the class has no field for. Jackson 3 ignores it by default, so a typo such as "prise" is skipped and price stays null.

A request has the typo prise. The program reads it three ways: with the default, with a strict mapper and with a tolerant class.

Example 1 · UnknownFieldsDemo.java: a typo, a strict mapper and a tolerant class

Runs in: the json-playground Maven project with Jackson 3.1.5

UnknownFieldsDemo.javaJava
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;import java.math.BigDecimal;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
public class UnknownFieldsDemo {
    record ProductRequest(String sku, BigDecimal price) { }
    // A client's view of someone else's response: extra fields are expected    @JsonIgnoreProperties(ignoreUnknown = true)    record RateResponse(String currency, BigDecimal rate) { }
    public static void main(String[] args) {        String withTypo = "{\"sku\": \"BK-CLEAN\", \"prise\": 449.00}";   // "prise" is a typo
        JsonMapper lenient = JsonMapper.builder().build();        System.out.println("Jackson 3 default: " + lenient.readValue(withTypo, ProductRequest.class));
        JsonMapper strict = JsonMapper.builder()                .enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)                .build();        try {            strict.readValue(withTypo, ProductRequest.class);        } catch (JacksonException e) {            System.out.println("Strict: " + e.getClass().getSimpleName() + ": " + e.getOriginalMessage());        }
        // The class-level annotation wins over the strict mapper        String rate = "{\"currency\": \"USD\", \"rate\": 0.0119, \"source\": \"RBI\", \"updatedAt\": \"2026-10-16\"}";        System.out.println("Strict + ignoreUnknown: " + strict.readValue(rate, RateResponse.class));
        System.out.println("Jackson 2 defaults fail on unknown: " + JsonMapper.builderWithJackson2Defaults().build()                .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));    }}
Output
Jackson 3 default: ProductRequest[sku=BK-CLEAN, price=null]
Strict: UnrecognizedPropertyException: Unrecognized property "prise" (class UnknownFieldsDemo$ProductRequest), not marked as ignorable
Strict + ignoreUnknown: RateResponse[currency=USD, rate=0.0119]
Jackson 2 defaults fail on unknown: true

What this code does

  • With Jackson 3 defaults the typo prise vanished and price is null: no error, just wrong data. The strict mapper names the unknown property instead.
  • @JsonIgnoreProperties(ignoreUnknown = true) let RateResponse skip source and updatedAt even on the strict mapper.
  • The last line confirms that Jackson 2's defaults failed on unknown properties.

Jackson 2 did the opposite and failed with UnrecognizedPropertyException; many older projects, and Spring Boot, changed that default. You choose per mapper with DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, and per class with @JsonIgnoreProperties(ignoreUnknown = true), which wins over a strict mapper.

A common split: be strict about JSON you own (your own files and requests, where an unknown key is a bug), and tolerant about other people's responses.

JsonMapper.builderWithJackson2Defaults() starts a builder with the old Jackson 2 settings, which helps when moving an old project to Jackson 3 step by step.

Missing fields become null or zero, and how to detect that

Missing field is a property the class has but the JSON leaves out. A class with setters keeps the default (null, 0 or false); a record gets null for an object component.

One product arrives with no stock. The program reads it five ways, with a setter class and with records.

Example 2 · MissingFieldsDemo.java: one missing field, five results

Runs in: the json-playground Maven project with Jackson 3.1.5

MissingFieldsDemo.javaJava
import com.fasterxml.jackson.annotation.JsonProperty;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
public class MissingFieldsDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    static class StockPojo {                 // a class with setters        private String sku;        private int stock;
        public StockPojo() { }
        public String getSku() { return sku; }        public void setSku(String sku) { this.sku = sku; }        public int getStock() { return stock; }        public void setStock(int stock) { this.stock = stock; }    }
    record StockBoxed(String sku, Integer stock) { }    record StockPrimitive(String sku, int stock) { }    record StockRequired(String sku, @JsonProperty(required = true) Integer stock) { }
    static void tryRead(JsonMapper mapper, Class<?> type) {        String json = "{\"sku\": \"ACC-PB20K\"}";            // no "stock" at all        try {            Object value = mapper.readValue(json, type);            if (value instanceof StockPojo p) {                System.out.println(type.getSimpleName() + ": sku=" + p.getSku() + ", stock=" + p.getStock());            } else {                System.out.println(type.getSimpleName() + ": " + value);            }        } catch (JacksonException e) {            System.out.println(type.getSimpleName() + ": " + e.getOriginalMessage());        }    }
    public static void main(String[] args) {        tryRead(MAPPER, StockPojo.class);        tryRead(MAPPER, StockBoxed.class);        tryRead(MAPPER, StockPrimitive.class);        tryRead(MAPPER, StockRequired.class);
        JsonMapper allRequired = MAPPER.rebuild()                .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES)                .build();        tryRead(allRequired, StockBoxed.class);    }}
Output
StockPojo: sku=ACC-PB20K, stock=0
StockBoxed: StockBoxed[sku=ACC-PB20K, stock=null]
StockPrimitive: Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
StockRequired: Missing required creator property 'stock' (index 1)
StockBoxed: Missing creator property 'stock' (index 1); `DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES` enabled

What this code does

  • The setter class shows stock=0, which looks like a real value: you cannot tell "none in stock" from "not sent". The record with Integer shows null, so you can.
  • The record with int fails, because a missing value would be null. required = true fails for just one component; FAIL_ON_MISSING_CREATOR_PROPERTIES makes every component required.

A record with a primitive component such as int fails in Jackson 3, because it cannot pass null to an int: Cannot map null into type int. To detect a missing value, use wrapper types (Integer, BigDecimal) so missing means null, not a fake 0.

To reject a missing value, mark the component @JsonProperty(required = true), or enable FAIL_ON_MISSING_CREATOR_PROPERTIES to make every record component required.

Predict the output

What does a missing field become?

Read the code and pick what it prints.

Round 1 of 3

The JSON has no "stock" key. What does p.stock() print?

record Product(String sku, Integer stock) { }
String json = "{\"sku\": \"ACC-AD141\"}";
Product p = MAPPER.readValue(json, Product.class);
System.out.println(p.stock());

null for primitives, wrong types and malformed JSON: the exceptions you get

JacksonException is the unchecked base class of every Jackson 3 error, so one catch handles them all. Its subclasses tell you what kind of problem it was.

Five bad requests give five different exceptions. The program prints the exception name and a short message for each.

Example 3 · ErrorKindsDemo.java: which exception for which problem

Runs in: the json-playground Maven project with Jackson 3.1.5

ErrorKindsDemo.javaJava
import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
public class ErrorKindsDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    record CartLine(String sku, int quantity) { }
    static void tryRead(String label, String json) {        tryRead(MAPPER, label, json);    }
    static void tryRead(JsonMapper mapper, String label, String json) {        try {            System.out.println(label + ": OK " + mapper.readValue(json, CartLine.class));        } catch (JacksonException e) {            System.out.println(label + ": " + e.getClass().getName());            System.out.println("   " + e.getOriginalMessage());        }    }
    public static void main(String[] args) {        tryRead("null for an int", "{\"sku\": \"BK-CLEAN\", \"quantity\": null}");        tryRead("wrong type     ", "{\"sku\": \"BK-CLEAN\", \"quantity\": \"two\"}");        tryRead("decimal for int", "{\"sku\": \"BK-CLEAN\", \"quantity\": 1.5}");        tryRead("malformed JSON ", "{\"sku\": \"BK-CLEAN\" \"quantity\": 2}");        tryRead("trailing text  ", "{\"sku\": \"BK-CLEAN\", \"quantity\": 2} OK");
        // 1.5 was cut to 1 without a word; make that an error        JsonMapper noFloatAsInt = MAPPER.rebuild().disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT).build();        tryRead(noFloatAsInt, "decimal, strict", "{\"sku\": \"BK-CLEAN\", \"quantity\": 1.5}");    }}
Output
null for an int: tools.jackson.databind.exc.MismatchedInputException
   Cannot map `null` into type `int` (set `DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES` to 'false' to allow)
wrong type     : tools.jackson.databind.exc.InvalidFormatException
   Cannot deserialize value of type `int` from String "two": not a valid `int` value
decimal for int: OK CartLine[sku=BK-CLEAN, quantity=1]
malformed JSON : tools.jackson.core.exc.StreamReadException
   Unexpected character ('"' (code 34)): was expecting comma to separate Object entries
trailing text  : tools.jackson.core.exc.StreamReadException
   Unrecognized token 'OK': was expecting (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
decimal, strict: tools.jackson.databind.exc.InvalidFormatException
   Cannot coerce Floating-point value (1.5) to `int` value (but could if coercion was enabled using `CoercionConfig`)

What this code does

  • Mapping problems come from tools.jackson.databind.exc; problems with the JSON text itself come from tools.jackson.core.exc.
  • 1.5 for an int quantity was quietly read as 1, a real bug for a shopping cart. With ACCEPT_FLOAT_AS_INT disabled it fails instead.

The subclass tells you the problem:

  • MismatchedInputException: the value cannot fit, such as null for an int or a string where a list was expected.
  • InvalidFormatException (a kind of mismatch): the value has the wrong format, such as "two" for an int or an unknown enum name.
  • UnrecognizedPropertyException: an unknown key, when the mapper is strict.
  • StreamReadException: not valid JSON at all, such as a missing comma or extra text after the end.

One quiet case gives no error: 1.5 for an int is cut to 1. Disable DeserializationFeature.ACCEPT_FLOAT_AS_INT to make it fail.

Checking required fields yourself after reading

Business rule is a rule about what a value means, such as a price above 0 or a SKU that is not blank. Jackson checks only shape and type, so your code checks business rules after reading.

Three requests are all valid JSON. The program reads each one, then collects every rule it breaks.

Example 4 · RequiredCheckDemo.java: business rules after reading

Runs in: the json-playground Maven project with Jackson 3.1.5

RequiredCheckDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class RequiredCheckDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    // Wrapper types, so a missing value shows up as null instead of 0    record NewProductRequest(String sku, String name, Integer categoryId, BigDecimal price, Integer stock) {
        List<String> problems() {            List<String> errors = new ArrayList<>();            if (sku == null || sku.isBlank()) errors.add("sku is required");            if (name == null || name.isBlank()) errors.add("name is required");            if (categoryId == null) errors.add("categoryId is required");            if (price == null) errors.add("price is required");            else if (price.signum() <= 0) errors.add("price must be more than 0");            if (stock != null && stock < 0) errors.add("stock cannot be negative");            return errors;        }
        int stockOrZero() {            return stock == null ? 0 : stock;     // stock is optional: 0 when missing        }    }
    static void check(String json) {        NewProductRequest req = MAPPER.readValue(json, NewProductRequest.class);        List<String> errors = req.problems();        if (errors.isEmpty()) {            System.out.println("OK: " + req.sku() + " with stock " + req.stockOrZero());        } else {            System.out.println("Rejected: " + String.join("; ", errors));        }    }
    public static void main(String[] args) {        check("{\"sku\": \"BK-DDIA\", \"name\": \"Designing Data-Intensive Apps\", \"categoryId\": 5, \"price\": 1299.00}");        check("{\"sku\": \"BK-DDIA\", \"categoryId\": 5, \"price\": 0}");        check("{\"name\": \"Mystery item\", \"stock\": -4}");    }}
Output
OK: BK-DDIA with stock 0
Rejected: name is required; price must be more than 0
Rejected: sku is required; categoryId is required; price is required; stock cannot be negative

What this code does

  • Jackson read all three requests without complaint: the JSON was valid and every value fitted its type. Only problems() knows the rules.
  • The third request gets four messages at once. stock is optional, so a missing stock becomes 0 only through stockOrZero(), a decision made in code, not by accident.

Jackson checks shape: is this valid JSON, and does each value fit its Java type? Rules about meaning belong to your code, right after reading and before anything is saved.

A simple pattern: wrapper types in the request record, then a method that collects every problem into a list, so the client sees all mistakes in one response instead of fixing them one at a time. Spring Boot's Bean Validation (@NotNull, @Positive) automates this in Section 15; the idea is the same.

Tolerant reader: why API clients should ignore fields they don't know

Tolerant reader is the rule that a client takes only the fields it needs from someone else's data and ignores the rest, so fields added later do not break it.

A courier's response gains two new fields. The program shows a client that keeps working, and one clear message for real errors.

Example 5 · TolerantReaderDemo.java: a courier client that survives new fields

Runs in: the json-playground Maven project with Jackson 3.1.5

TolerantReaderDemo.javaJava
import java.util.List;import tools.jackson.core.JacksonException;import tools.jackson.core.exc.StreamReadException;import tools.jackson.databind.exc.InvalidFormatException;import tools.jackson.databind.exc.MismatchedInputException;import tools.jackson.databind.exc.UnrecognizedPropertyException;import tools.jackson.databind.json.JsonMapper;
public class TolerantReaderDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    record Tracking(String awb, String status, List<String> cities) { }
    // One place that turns Jackson's messages into text for people    static String friendlyMessage(JacksonException e) {        String field = e.getPath().isEmpty() ? null : e.getPath().get(e.getPath().size() - 1).getPropertyName();        if (e instanceof UnrecognizedPropertyException u) {            return "Unknown field '" + u.getPropertyName() + "'";        }        if (e instanceof InvalidFormatException f) {            return "Field '" + field + "' has a wrong value: " + f.getValue();        }        if (e instanceof MismatchedInputException) {            return field == null ? "The JSON has the wrong shape" : "Field '" + field + "' is missing or has the wrong type";        }        if (e instanceof StreamReadException) {            return "Not valid JSON (line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr() + ")";        }        return "Could not read the data";    }
    static void read(String json) {        try {            System.out.println("OK: " + MAPPER.readValue(json, Tracking.class));        } catch (JacksonException e) {            System.out.println("Error: " + friendlyMessage(e));        }    }
    public static void main(String[] args) {        // Version 1 of the courier response        read("{\"awb\": \"SL7788123\", \"status\": \"IN_TRANSIT\", \"cities\": [\"Chennai\", \"Vellore\"]}");        // Version 2 added two fields: an old client keeps working        read("{\"awb\": \"SL7788123\", \"status\": \"IN_TRANSIT\", \"cities\": [\"Chennai\"],"                + " \"etaHours\": 18, \"carbonGrams\": 420}");        read("{\"awb\": \"SL7788123\", \"status\": \"IN_TRANSIT\", \"cities\": \"Chennai\"}");        read("{\"awb\": \"SL7788123\", \"status\": IN_TRANSIT}");    }}
Output
OK: Tracking[awb=SL7788123, status=IN_TRANSIT, cities=[Chennai, Vellore]]
OK: Tracking[awb=SL7788123, status=IN_TRANSIT, cities=[Chennai]]
Error: Field 'cities' is missing or has the wrong type
Error: Not valid JSON (line 1, column 32)

What this code does

  • Version 2 of the response added etaHours and carbonGrams; the client ignored them and kept working.
  • When a field the client needs is wrong (cities is a string, not a list) or the JSON is broken, friendlyMessage turns the exception into one clear line. Its checks start with the most specific exception types, because InvalidFormatException is also a MismatchedInputException.

APIs grow: a courier adds etaHours next month. A tolerant client keeps working; a strict one breaks on the provider's next release, even though nothing it uses changed.

Tolerant does not mean careless. Still fail on what you actually need: a missing or wrong-typed field you use is an error. Catch JacksonException in one place and turn it into a message a person can act on, such as Field 'cities' has the wrong type, instead of showing Jackson's raw text or a stack trace.

Next step

Check your understanding

12 quick questions