Skip to lesson

Lists, maps and nested objects

A shop's API returns a list of products, an order that holds a customer and items, or a webhook whose shape you do not fully know. Flat objects are rare, so lists and nested data must map too.

Serializing a List of products to a JSON array

JSON array is an ordered list of values inside square brackets. Jackson writes a Java List, Set or array as a JSON array, and an empty list as [], never null.

Three products in a List become one JSON array. The program writes the list, and an empty one.

Example 1 · ProductListDemo.java: a List becomes a JSON array

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

ProductListDemo.javaJava
import java.math.BigDecimal;import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class ProductListDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    static class Product {        private String sku;        private String name;        private BigDecimal price;        private int stock;
        public Product() { }
        Product(String sku, String name, BigDecimal price, int stock) {            this.sku = sku;            this.name = name;            this.price = price;            this.stock = stock;        }
        public String getSku() { return sku; }        public void setSku(String sku) { this.sku = sku; }        public String getName() { return name; }        public void setName(String name) { this.name = name; }        public BigDecimal getPrice() { return price; }        public void setPrice(BigDecimal price) { this.price = price; }        public int getStock() { return stock; }        public void setStock(int stock) { this.stock = stock; }    }
    public static void main(String[] args) {        List<Product> mobiles = List.of(                new Product("MOB-RN13", "Redmi Note 13 5G", new BigDecimal("17999.00"), 40),                new Product("MOB-GM35", "Samsung Galaxy M35", new BigDecimal("19999.00"), 25),                new Product("MOB-IP15", "iPhone 15 128GB", new BigDecimal("69900.00"), 8));
        System.out.println(MAPPER.writeValueAsString(mobiles));        System.out.println(MAPPER.writeValueAsString(List.of()));        System.out.println(MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(mobiles.subList(0, 1)));    }}
Output
[{"name":"Redmi Note 13 5G","price":17999.00,"sku":"MOB-RN13","stock":40},{"name":"Samsung Galaxy M35","price":19999.00,"sku":"MOB-GM35","stock":25},{"name":"iPhone 15 128GB","price":69900.00,"sku":"MOB-IP15","stock":8}]
[]
[ {
  "name" : "Redmi Note 13 5G",
  "price" : 17999.00,
  "sku" : "MOB-RN13",
  "stock" : 40
} ]

What this code does

  • The three products became three JSON objects inside one array, each written exactly like a single product.
  • An empty list is written as []. The pretty printer puts [ { on one line: that is its normal layout for an array of objects.

Jackson writes [, then each element the same way it would write it alone, separated by commas, then ]. This is what a "list products" API returns: one writeValueAsString(list) call handles every element and every nested value inside it.

Reading a JSON array back: why List.class loses the type, and TypeReference

Type erasure is Java removing generic types after compiling, so at run time a List<Product> is only a List. That is why List<Product>.class does not exist.

Reading an array with List.class looks fine but fills the list with maps. The first program shows the mistake, the second the fix.

Reading a JSON array of products. With List.class Jackson is not told the element type, because generics are erased at run time, so it fills the list with LinkedHashMap objects and the code fails later with a ClassCastException.
Generics are erased at run time, so the type must be passed in.

Example 2 · ListClassMistakeDemo.java: List.class gives maps, not products

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

ListClassMistakeDemo.javaJava
import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class ListClassMistakeDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    static class Product {        private String sku;        private int stock;
        public Product() { }
        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; }    }
    public static void main(String[] args) {        String json = """                [{"sku": "ACC-AD141", "stock": 120},                 {"sku": "ACC-PB20K", "stock": 60}]                """;
        List<?> products = MAPPER.readValue(json, List.class);   // compiles and runs...        System.out.println("Size: " + products.size());        System.out.println("First item: " + products.get(0));        System.out.println("Its class: " + products.get(0).getClass().getName());
        try {            Product first = (Product) products.get(0);            // ...but this is not a Product            System.out.println(first.getSku());        } catch (ClassCastException e) {            System.out.println("ClassCastException: " + e.getMessage());        }    }}
Output
Size: 2
First item: {sku=ACC-AD141, stock=120}
Its class: java.util.LinkedHashMap
ClassCastException: class java.util.LinkedHashMap cannot be cast to class ListClassMistakeDemo$Product (java.util.LinkedHashMap is in module java.base of loader 'bootstrap'; ListClassMistakeDemo$Product is in unnamed module of loader 'app')

What this code does

  • Reading worked and the size is right, which is why this bug survives a quick test. Each element is a LinkedHashMap that prints as {sku=ACC-AD141, stock=120}.
  • The crash comes only when the code casts an element to Product, far from the line that caused it.

Example 3 · TypeReferenceDemo.java: the fix

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

TypeReferenceDemo.javaJava
import java.util.List;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.json.JsonMapper;
public class TypeReferenceDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    // One TypeReference, written once and reused    static final TypeReference<List<Product>> PRODUCT_LIST = new TypeReference<>() { };
    static class Product {        private String sku;        private int stock;
        public Product() { }
        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; }    }
    public static void main(String[] args) {        String json = """                [{"sku": "ACC-AD141", "stock": 120},                 {"sku": "ACC-PB20K", "stock": 60},                 {"sku": "ACC-M331", "stock": 0}]                """;
        List<Product> products = MAPPER.readValue(json, PRODUCT_LIST);        int total = 0;        for (Product p : products) {            System.out.println(p.getSku() + " -> " + p.getStock());            total += p.getStock();        }        System.out.println("Units in stock: " + total);
        // An array type also keeps the element type        Product[] asArray = MAPPER.readValue(json, Product[].class);        System.out.println("As array: " + asArray.length + " products, last is " + asArray[2].getSku());    }}
Output
ACC-AD141 -> 120
ACC-PB20K -> 60
ACC-M331 -> 0
Units in stock: 180
As array: 3 products, last is ACC-M331

What this code does

  • PRODUCT_LIST tells Jackson the full type List<Product>, so every element is a real Product and the loop needs no cast. The diamond <> works here from Java 9.
  • Product[].class works too, because array types are not erased. Lists are usually easier to work with afterwards.

Jackson is only told "a list", not "a list of what", so it fills the list with LinkedHashMaps, one map per JSON object, and your code crashes later with a ClassCastException when it treats one as a Product.

TypeReference carries the full generic type to Jackson: new TypeReference<List<Product>>() { }. The { } makes a tiny anonymous subclass, and Java does keep the generic type of a subclass's parent, which Jackson reads. Store it in a static final field and reuse it. For a plain array, Product[].class also keeps the element type.

Fix the error

Keep the element type when reading

Read the error, then pick the line that fixes it.

Round 1 of 2

The list reads fine but the loop crashes. Fix line 1.

List<Product> list = MAPPER.readValue(json, List.class);
for (Product p : list) {
System.out.println(p.sku());
}

Error

ClassCastException: class java.util.LinkedHashMap cannot be cast to class Product

Nested objects: an order with its customer and a list of items

Nested object is a JSON object inside another JSON object. Jackson maps it to a field whose type is another class, to any depth.

ShopLite order 14 holds a customer and a list of items. One readValue call builds all the objects.

Example 4 · NestedOrderDemo.java: ShopLite order 14 with its customer and items

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

NestedOrderDemo.javaJava
import java.math.BigDecimal;import java.util.List;import tools.jackson.databind.json.JsonMapper;
public class NestedOrderDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    static class Customer {        private String fullName;        private String email;
        public Customer() { }
        public String getFullName() { return fullName; }        public void setFullName(String fullName) { this.fullName = fullName; }        public String getEmail() { return email; }        public void setEmail(String email) { this.email = email; }    }
    static class OrderItem {        private String sku;        private int quantity;        private BigDecimal unitPrice;
        public OrderItem() { }
        public String getSku() { return sku; }        public void setSku(String sku) { this.sku = sku; }        public int getQuantity() { return quantity; }        public void setQuantity(int quantity) { this.quantity = quantity; }        public BigDecimal getUnitPrice() { return unitPrice; }        public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; }
        BigDecimal lineTotal() {            return unitPrice.multiply(BigDecimal.valueOf(quantity));        }    }
    static class Order {        private int orderId;        private String status;        private Customer customer;          // a nested object        private List<OrderItem> items;      // a nested array of objects
        public Order() { }
        public int getOrderId() { return orderId; }        public void setOrderId(int orderId) { this.orderId = orderId; }        public String getStatus() { return status; }        public void setStatus(String status) { this.status = status; }        public Customer getCustomer() { return customer; }        public void setCustomer(Customer customer) { this.customer = customer; }        public List<OrderItem> getItems() { return items; }        public void setItems(List<OrderItem> items) { this.items = items; }    }
    public static void main(String[] args) {        String json = """                {                  "orderId": 14,                  "status": "SHIPPED",                  "customer": { "fullName": "Ravi Kumar", "email": "ravi.kumar@example.com" },                  "items": [                    { "sku": "MOB-RN13", "quantity": 1, "unitPrice": 17999.00 },                    { "sku": "ACC-AD141", "quantity": 1, "unitPrice": 1299.00 }                  ]                }                """;
        Order order = MAPPER.readValue(json, Order.class);        System.out.println("Order " + order.getOrderId() + " for " + order.getCustomer().getFullName()                + " (" + order.getStatus() + ")");
        BigDecimal total = BigDecimal.ZERO;        for (OrderItem item : order.getItems()) {            System.out.println("  " + item.getSku() + " x " + item.getQuantity() + " = Rs. " + item.lineTotal());            total = total.add(item.lineTotal());        }        System.out.println("Total: Rs. " + total);
        System.out.println(MAPPER.writeValueAsString(order));    }}
Output
Order 14 for Ravi Kumar (SHIPPED)
  MOB-RN13 x 1 = Rs. 17999.00
  ACC-AD141 x 1 = Rs. 1299.00
Total: Rs. 19298.00
{"customer":{"email":"ravi.kumar@example.com","fullName":"Ravi Kumar"},"items":[{"quantity":1,"sku":"MOB-RN13","unitPrice":17999.00},{"quantity":1,"sku":"ACC-AD141","unitPrice":1299.00}],"orderId":14,"status":"SHIPPED"}

What this code does

  • One readValue call built four objects: the Order, its Customer and two OrderItems. The field type List<OrderItem> told Jackson what each array element is.
  • Totals use BigDecimal.multiply and add, so 17999.00 + 1299.00 is exactly 19298.00. Writing the order back nests the objects the same way, keys in alphabetical order at each level.

If Order has a Customer customer field and a List<OrderItem> items field, Jackson reads "customer": {...} into a Customer and "items": [...] into a list of OrderItems. Inside a class the field's declared type tells Jackson the element type, so List<OrderItem> needs no TypeReference.

Each nested class follows the same rules as before: a no-arg constructor and setters for reading, getters for writing.

Maps and the JsonNode tree for JSON whose shape you don't know

JsonNode is Jackson's tree of JSON values: every value is a node that knows its JSON type. readTree(json) builds the tree, and no Java class is needed.

A payment webhook arrives with no matching class. The program reads it as a Map and as a JsonNode tree.

Example 5 · MapAndTreeDemo.java: a webhook as a Map and as a tree

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

MapAndTreeDemo.javaJava
import java.util.Map;import tools.jackson.core.type.TypeReference;import tools.jackson.databind.JsonNode;import tools.jackson.databind.json.JsonMapper;
public class MapAndTreeDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    public static void main(String[] args) {        // A payment gateway's webhook: you know only some of its fields        String json = """                {"event": "payment.captured", "amount": 2499, "currency": "INR",                 "method": {"type": "upi", "vpa": "priya@okbank"}, "retries": 0, "test": false}                """;
        // 1. As a Map: each JSON type becomes a plain Java type        Map<String, Object> map = MAPPER.readValue(json, new TypeReference<Map<String, Object>>() { });        for (Map.Entry<String, Object> e : map.entrySet()) {            System.out.println(e.getKey() + " -> " + e.getValue().getClass().getSimpleName());        }
        // 2. As a tree: every value is a JsonNode that knows its JSON type        JsonNode root = MAPPER.readTree(json);        System.out.println("Fields: " + root.propertyNames());        for (Map.Entry<String, JsonNode> e : root.properties()) {            System.out.println(e.getKey() + " is " + e.getValue().getNodeType());        }        System.out.println("Paid " + root.get("amount").asInt() + " " + root.get("currency").asString());    }}
Output
event -> String
amount -> Integer
currency -> String
method -> LinkedHashMap
retries -> Integer
test -> Boolean
Fields: [event, amount, currency, method, retries, test]
event is STRING
amount is NUMBER
currency is STRING
method is OBJECT
retries is NUMBER
test is BOOLEAN
Paid 2499 INR

What this code does

  • In the map, the nested method object became a LinkedHashMap and the numbers became Integer. You must cast every value you take out, which is easy to get wrong.
  • In the tree, every value is a JsonNode whose getNodeType() is the JSON type. asInt() and asString() convert a node without casts. LinkedHashMap and properties() both keep the order of the JSON.

Sometimes you have no class for the JSON: a webhook with many optional fields, settings with any keys, or a response you only want to look into. A Map<String, Object>, read with a TypeReference, turns JSON objects into LinkedHashMaps, arrays into ArrayLists, strings into String, whole numbers into Integer or Long, decimals into Double and true/false into Boolean.

A tree from readTree(json) keeps every value as a node; propertyNames() and properties() list an object's keys and values.

Reading one value deep inside a response with path() and get()

Missing node is the placeholder JsonNode that path() returns when a field does not exist, so a chain of path() calls never throws.

A courier response is nested three levels deep. The program picks three values out of it and shows what a missing field does.

Example 6 · PathAndGetDemo.java: three values from a courier response

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

PathAndGetDemo.javaJava
import tools.jackson.databind.JsonNode;import tools.jackson.databind.json.JsonMapper;
public class PathAndGetDemo {
    static final JsonMapper MAPPER = JsonMapper.builder().build();
    public static void main(String[] args) {        String json = """                {                  "data": {                    "awb": "SL7788123",                    "shipment": {                      "status": "IN_TRANSIT",                      "events": [                        {"city": "Chennai", "time": "2026-09-22T08:10:00+05:30"},                        {"city": "Vellore", "time": "2026-09-22T14:45:00+05:30"}                      ]                    }                  }                }                """;        JsonNode root = MAPPER.readTree(json);
        // path() never returns null: a missing step gives a "missing node"        String status = root.path("data").path("shipment").path("status").asString();        String lastCity = root.path("data").path("shipment").path("events").path(1).path("city").asString();        String eta = root.path("data").path("shipment").path("eta").asString("not known yet");        System.out.println("Status: " + status);        System.out.println("Last scan: " + lastCity);        System.out.println("ETA: " + eta);
        // The same value with a JSON Pointer: one string with the whole path        System.out.println("AWB: " + root.at("/data/awb").asString());        System.out.println("Events: " + root.at("/data/shipment/events").size());
        // get() returns null for a missing field, so the next call crashes        JsonNode etaNode = root.get("data").get("shipment").get("eta");        System.out.println("get(\"eta\") returned " + etaNode);        try {            System.out.println(etaNode.asString());        } catch (NullPointerException e) {            System.out.println("NullPointerException: get() gave null for a missing field");        }    }}
Output
Status: IN_TRANSIT
Last scan: Vellore
ETA: not known yet
AWB: SL7788123
Events: 2
get("eta") returned null
NullPointerException: get() gave null for a missing field

What this code does

  • path(1) picked the second event (indexes start at 0). The response has no eta, so path("eta") gave a missing node and asString("not known yet") returned the default.
  • at("/data/awb") is a JSON Pointer: the same walk as path("data").path("awb") in one string.
  • get("eta") returned null, and calling asString() on it threw NullPointerException. With path the same chain is safe.

path("name") returns the child, or a missing node when it does not exist; path(1) steps into an array by index. get("name") returns null for a missing child, so the next call in a chain throws NullPointerException.

At the end, asString(), asInt() or asDecimal() turn the node into a Java value; asString("default") gives a default for a missing node. at("/data/shipment/status") does the whole walk with one JSON Pointer string. Use path or at when a field may be absent, and get only when it must exist.

Next step

Check your understanding

11 quick questions