Skip to lesson

Practice: JSON and Jackson

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Five mistakes cause most JSON bugs: invalid text, a class Jackson cannot build, a lost generic type, dates written as arrays, and unknown or missing fields. Fix each one before you move on.

Fixing invalid JSON documents

Four small documents each break one rule. The validator stops at the first error, so a file with three mistakes needs three rounds.

Example 1 · fest-broken.json: three mistakes, one shown at a time

JSON
{  "fest": "Techno Utsav 2026",  "events": [    { "name": "Hackathon", "fee": 200, "teamSize": 4 },    { "name": 'Quiz', "fee": 100, "teamSize": 2 },  ],  "open": True}
python -m json.tool --indent 2 fest-broken.json
Expecting value: line 5 column 15 (char 117)

What this code does

  • The first error is 'Quiz' on line 5. After fixing it, the validator stops at the trailing comma after the second event, and then at True.
  • Practice 1 asks you to fix all three and confirm the clean result.

Work from the reported line and column, and look just before that spot. Expecting value usually means a single-quoted string, True or None; Illegal trailing comma means a comma before ] or }; Expecting ',' delimiter means a comma is missing at the end of the previous line. Review: JSON syntax (opens in a new tab).

Mapping given JSON to records and back

Mapping given JSON means writing the Java types that match it. The program maps a category and its products to records.

Example 2 · RecordMappingDemo.java: a category with its products

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

RecordMappingDemo.javaJava
import java.math.BigDecimal;import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class RecordMappingDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    // Step 1: one record per JSON object, one component per key    record ProductDto(String sku, String name, BigDecimal price, int stock, boolean active) { }    record CategoryDto(int id, String name, String parent, List<ProductDto> products) { }
    public static void main(String[] args) {        String json = """                {"id": 4, "name": "Accessories", "parent": "Electronics",                 "products": [                   {"sku": "ACC-AD141", "name": "boAt Airdopes 141", "price": 1299.00, "stock": 120, "active": true},                   {"sku": "ACC-M331", "name": "Logitech M331 Silent Mouse", "price": 849.00, "stock": 0, "active": true}                 ]}                """;
        // Step 2: read, use, write back        CategoryDto accessories = MAPPER.readValue(json, CategoryDto.class);        for (ProductDto p : accessories.products()) {            System.out.println(p.sku() + (p.stock() == 0 ? " is out of stock" : " has " + p.stock() + " units"));        }        System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(accessories.products().get(1)));    }}
Output
ACC-AD141 has 120 units
ACC-M331 is out of stock
{
  "sku" : "ACC-M331",
  "name" : "Logitech M331 Silent Mouse",
  "price" : 849.00,
  "stock" : 0,
  "active" : true
}

What this code does

  • Two records match the two kinds of JSON objects; List<ProductDto> matches the products array, and BigDecimal keeps 849.00 exact.
  • Writing one product back gives its keys in the record's component order, the same order as the input.

The method is mechanical: one record per JSON object, one component per key with the same name, a List<...> for every array, BigDecimal for money, LocalDate or Instant for dates, an enum for a fixed set of strings, and a wrapper type such as Integer where a value may be missing. Then read with readValue, use the values, and write back with writeValueAsString; records keep their component order when written, so the output looks like the input.

Review: Records, dates and money (opens in a new tab).

Broken mappings: missing constructor, wrong generic type, date as array

Three mapping bugs appear again and again. The program shows each bug and its fix.

Example 3 · BrokenMappingsDemo.java: three bugs and their fixes

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

BrokenMappingsDemo.javaJava
import java.time.LocalDate;import java.util.List;import tools.jackson.core.JacksonException;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.cfg.DateTimeFeature;import tools.jackson.databind.json.JsonMapper;
public class BrokenMappingsDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    // Bug 1: a class with only a two-argument constructor    static class CouponClass {        private final String code;        private final int percentOff;
        CouponClass(String code, int percentOff) {            this.code = code;            this.percentOff = percentOff;        }
        public String getCode() { return code; }        public int getPercentOff() { return percentOff; }    }
    record Coupon(String code, int percentOff) { }
    record Sale(String name, LocalDate startsOn) { }
    public static void main(String[] args) {        String coupon = "{\"code\": \"FEST20\", \"percentOff\": 20}";        try {            MAPPER.readValue(coupon, CouponClass.class);        } catch (JacksonException e) {            System.out.println("Bug 1: " + e.getOriginalMessage());        }        System.out.println("Fix 1: " + MAPPER.readValue(coupon, Coupon.class));
        // Bug 2: List.class gives maps, so the cast fails        String coupons = "[{\"code\": \"FEST20\", \"percentOff\": 20}, {\"code\": \"HOSTEL10\", \"percentOff\": 10}]";        List<?> raw = MAPPER.readValue(coupons, List.class);        try {            Coupon first = (Coupon) raw.get(0);            System.out.println(first.code());        } catch (ClassCastException e) {            System.out.println("Bug 2: element is a " + raw.get(0).getClass().getSimpleName() + ", not a Coupon");        }        List<Coupon> typed = MAPPER.readValue(coupons, new TypeReference<List<Coupon>>() { });        System.out.println("Fix 2: " + typed.get(1).code());
        // Bug 3: a mapper copied from an old project writes dates as arrays        JsonMapper oldStyle = JsonMapper.builder().enable(DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS).build();        Sale diwali = new Sale("Diwali Sale", LocalDate.of(2026, 11, 1));        System.out.println("Bug 3: " + oldStyle.writeValueAsString(diwali));        System.out.println("Fix 3: " + MAPPER.writeValueAsString(diwali));    }}
Output
Bug 1: Cannot construct instance of `BrokenMappingsDemo$CouponClass` (no Creators, like default constructor, exist): cannot deserialize from Object value (no delegate- or property-based Creator)
Fix 1: Coupon[code=FEST20, percentOff=20]
Bug 2: element is a LinkedHashMap, not a Coupon
Fix 2: HOSTEL10
Bug 3: {"name":"Diwali Sale","startsOn":[2026,11,1]}
Fix 3: {"name":"Diwali Sale","startsOn":"2026-11-01"}

What this code does

  • Bug 1 is a definition problem: Jackson cannot create CouponClass. The record version works with the same JSON.
  • Bug 2 only shows when an element is used. Bug 3 is not an error at all, just JSON that clients find hard to use; the default mapper writes ISO text.

The three bugs and their fixes:

  • Missing constructor: a class with only a constructor that takes arguments fails with no Creators, like default constructor, exist. Turn it into a record, or add a no-arg constructor and setters.
  • Wrong generic type: readValue(json, List.class) or Map.class fills the collection with LinkedHashMaps, and the code crashes later with ClassCastException. Use a TypeReference with the full type.
  • Date as array: [2026,11,1] instead of "2026-11-01" comes from WRITE_DATES_AS_TIMESTAMPS, the Jackson 2 default copied into a new mapper. Use Jackson 3's default.

Review: Lists, maps and nested objects (opens in a new tab).

Find the bug

Spot the mapping bug

Select the line that is wrong.

Reading a Coupon crashes with "no Creators exist". Tap the line.

Round 1 of 3

Interview drill: ObjectMapper reuse, @JsonIgnore, unknown properties

Three questions come up in almost every Java backend interview that touches JSON. The program answers them in code.

Example 4 · InterviewDrillDemo.java: the three answers in code

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

InterviewDrillDemo.javaJava
import com.fasterxml.jackson.annotation.JsonIgnore;import tools.jackson.core.JacksonException;import tools.jackson.databind.DeserializationFeature;import tools.jackson.databind.json.JsonMapper;
public class InterviewDrillDemo {
    // Q1: one mapper, built once, shared by everyone    static final JsonMapper MAPPER = JsonMapper.builder().build();
    // Q2: the hash stays on the server    record Customer(int id, String fullName, @JsonIgnore String passwordHash) { }
    public static void main(String[] args) {        Customer kabir = new Customer(4, "Kabir Singh", "$2a$10$hashhashhash");        System.out.println("Q2: " + MAPPER.writeValueAsString(kabir));
        // Q3: unknown properties, lenient by default in Jackson 3, strict on request        String json = "{\"id\": 4, \"fullName\": \"Kabir Singh\", \"role\": \"ADMIN\"}";        System.out.println("Q3 default: " + MAPPER.readValue(json, Customer.class));        JsonMapper strict = MAPPER.rebuild().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build();        try {            strict.readValue(json, Customer.class);        } catch (JacksonException e) {            System.out.println("Q3 strict: " + e.getClass().getSimpleName());        }    }}
Output
Q2: {"id":4,"fullName":"Kabir Singh"}
Q3 default: Customer[id=4, fullName=Kabir Singh, passwordHash=null]
Q3 strict: UnrecognizedPropertyException

What this code does

  • One static final mapper serves the whole program; rebuild() makes the strict copy without touching it.
  • The hash never appears in the output. The unknown role key is skipped by default and rejected by the strict copy, which is how a client could otherwise try to make itself an admin.

Each has a short answer you should be able to say and show in code:

  • Reuse: one mapper, built once and shared; it is thread-safe and costly to build.
  • @JsonIgnore: keeps a property out of JSON in both directions, for secrets such as password hashes; a response DTO without the field is safer still.
  • Unknown properties: Jackson 3 ignores them by default, Jackson 2 failed. Be strict for JSON you own and tolerant for other people's.

Finish up

Mark complete & continue

Next: Mini project: ShopLite catalogue to JSON and back