Skip to main content

Jackson Streaming API and JsonNode (Jackson 3): Process Huge JSON Without Running Out of Memory

A real 1 GiB JSON file, four ways to read it with Jackson 3.2.4, and a memory graph. JsonParser streaming finished in a 32 MB heap; readTree ran out of memory at every limit up to 4 GB. Includes the nested-object trap, truncated files, and a decision table.

It is 2 a.m., a nightly job reads an export file with ObjectMapper.readTree(), and the JVM dies with java.lang.OutOfMemoryError: Java heap space. The file was 300 MB last month. Nobody changed the code. This post is about why that happens and the fix: reading JSON as a stream of tokens, so memory depends on how much JSON you hold at once and not on how big the file is.

Everything here is Jackson 3 (tools.jackson packages). I generated a real 1 GiB file, ran four ways of reading it under fixed heap limits, and put the numbers, the failures and a memory graph below. If you are still on Jackson 2, the class names differ and the Jackson 2 to Jackson 3 migration guide maps old to new; the Jackson 3 vs Jackson 2 comparison covers the behaviour changes.

Versions tested. Jackson 3.2.4 (tools.jackson.core:jackson-databind, current GA on Maven Central, published 2026-10-18, read from maven-metadata.xml), Temurin JDK 25.0.5+8 (LTS), Maven 3.9.11, on a 2-CPU / 8 GB container. jackson-annotations stays on com.fasterxml.jackson.core at 2.22. Jackson 3 needs Java 17 or newer.

Runnable code: the new benchmark is the streaming-huge-json module of jackson3-by-example. The smaller examples are in the same repository: G01 the streaming filter, G02 the generator, G03 the tree model and G04 all three approaches measured on a 20 MB file, with captured output in docs/part6-streaming.md.

The streaming and tree APIs took more renames than any other area in the Jackson 3 move, so here they are in one place: JsonFactory is now in tools.jackson.core.json (note the extra .json), getCurrentName() → currentName(), getText() → getString(), JsonToken.FIELD_NAME → JsonToken.PROPERTY_NAME, writeNumberField/writeStringField → writeNumberProperty/writeStringProperty, JsonNode.asText() → asString(), and createParser/createGenerator now take an ObjectReadContext/ObjectWriteContext.

Why a big JSON file kills the heap, and what streaming changes

For most applications, ObjectMapper.readValue() and writeValueAsString() are all you need. But when JSON files reach hundreds of megabytes, or when you need to work with dynamic JSON whose schema you do not know at compile time, Jackson offers two lower-level APIs that give you full control: the Streaming API (JsonParser / JsonGenerator) and the Tree Model (JsonNode). This guide explains when to use each and shows practical examples for both.

The key idea is that JSON text and JSON objects are different sizes. A number such as 458856 is six bytes in the file. As a JsonNode it is an object with a header and a field, referenced from a parent node that is itself an object with a map inside. When you call readTree or readValue, Jackson builds all of that for the whole document before it returns anything. Streaming skips the building: the parser hands you one token, you look at it, you move on, and the garbage collector reclaims the previous token.

Streaming: the file flows past a tiny window JSON file1 GiB on disk JsonParserone token at a time your countersrecords, errors, latency sum Heap holds: the current token, a read buffer, a few integers. Size of the file does not appear in that list. Tree model: the whole file is rebuilt in memory JSON file1 GiB on disk readTree(file)builds every node ObjectNode, TextNode, IntNode…4,088,325 records x ~13 nodes each,all alive until readTree returns Each node is a Java object with a header, pointers and, for objects, a map. The same bytes cost several times more as objects than as text. The benchmark below measures how many times more.
Figure 1. Same file, two memory shapes.

Figure 1 is the whole argument. In the top row nothing in the heap is proportional to the file. In the bottom row everything is. The rest of this post puts numbers on the bottom row and then shows how to live in the top one without tripping over its sharp edges.

Going deeper: what a “token” is

A JsonParser yields a JsonToken each time you call nextToken(): START_OBJECT, PROPERTY_NAME, VALUE_STRING, VALUE_NUMBER_INT, START_ARRAY, END_OBJECT and so on. For {"level":"ERROR","latencyMs":71} the stream is START_OBJECT, PROPERTY_NAME (level), VALUE_STRING (ERROR), PROPERTY_NAME (latencyMs), VALUE_NUMBER_INT (71), END_OBJECT. After each call the parser exposes the current token’s text and numeric value (getString(), getIntValue()) and its name (currentName()). That is all the state you have; if you need something from an earlier token you must have kept it in a variable.

Reference: the JSON grammar is in RFC 8259; Jackson’s API is in the jackson-core 3.2.4 Javadoc and jackson-databind 3.2.4 Javadoc.

What happens to a 1 GiB file: the failure first

The test file is a JSON array of 4,088,325 log records, 1,073,741,995 bytes, generated by GenerateHugeJson.java with a fixed random seed so every run produces identical bytes (I regenerated it once and compared with cmp: identical). Each record has a timestamp, level, service, host, message, latency, a nested user object and a three-element tags array, which is a realistic shape rather than three flat fields. The job is deliberately simple: count the ERROR records and sum their latency. Every approach must print the same three numbers, and they do.

The runner is Scan.java, one fresh JVM per run, with -Xmx set from outside. The full ladder is in output/bench.txt:

stream  -Xmx=   32 MB  OK    records=4,088,325 errors=81,728 errLatencySum=81,712,926    8,898 ms  peakUsed=   19 MB
stream  -Xmx= 1024 MB  OK    records=4,088,325 errors=81,728 errLatencySum=81,712,926   12,047 ms  peakUsed=   56 MB
hybrid  -Xmx=   32 MB  OK    records=4,088,325 errors=81,728 errLatencySum=81,712,926   19,128 ms  peakUsed=   20 MB
tree    -Xmx=   64 MB  FAIL  java.lang.OutOfMemoryError: Java heap space  after 4,278 ms
tree    -Xmx= 4096 MB  FAIL  java.lang.OutOfMemoryError: Java heap space  after 78,019 ms
tree    -Xmx= 6144 MB  KILLED  no Java output, exit=137 (SIGKILL by the OS: the heap limit was larger than free RAM)
bind    -Xmx= 2048 MB  FAIL  java.lang.OutOfMemoryError: Java heap space  after 177,038 ms
bind    -Xmx= 3072 MB  OK    records=4,088,325 errors=81,728 errLatencySum=81,712,926   32,180 ms  peakUsed=2,943 MB

Read the pattern, not the milliseconds. Streaming finished the whole file in a 32 MB heap, 3% of the file size. readValue into a List of records needed between 2 GB and 3 GB. readTree never finished: it ran out of memory at every limit up to 4 GB, and at 6 GB the operating system killed the JVM before Java could say anything. I take that to mean the tree for this file is larger than 4 GB, four or more times the file size, but I did not find the exact figure because the machine has 8 GB of RAM.

Peak heap used on a 1 GiB file (smaller is better) stream JsonParser, skipChildren()peak 19 MB at -Xmx32m hybrid JsonParser + readValueAs(record)peak 20 MB at -Xmx32m bind readValue(file, List<LogEntry>)peak 2,943 MB at -Xmx3072m (failed at 2048m) tree readTree(file)no run finished: OutOfMemoryError at every limit up to 4,096 MB file size, 1,024 MB Bars share one linear scale, 0 to 4,096 MB. The streaming bars are thin because 19 MB is 0.5% of 4,096 MB. Peak is sampled (total − free) heap, so it includes garbage not yet collected: it overstates the streaming rows, if anything.
Figure 2. Measured on one run, 2 CPUs, 8 GB RAM, Temurin 25.0.5, Jackson 3.2.4.

Figure 2 shows why readTree is the expensive choice: the same information as records took about 3 GB, as tree nodes it took more than 4 GB. The thin green bars are the point of the post. They are not a rounding error, they are what constant memory looks like.

Which -Xmx limits each approach survived (heap limit in MB) 32 64 128 256 1024 2048 3072 4096 6144 stream pass pass pass not run pass not run not run not run not run hybrid pass pass pass not run pass not run not run not run not run tree not run OOM not run OOM OOM OOM OOM OOM killed bind not run OOM not run OOM OOM OOM pass not run not run Streaming rows were only run at four limits because they never came close to failing; tree and bind climbed until success. “killed” = the JVM printed nothing and exited 137: a 6 GB heap on an 8 GB box, and the OS killed the process.
Figure 3. The same ladder as the table in output/bench.txt.

Figure 3 is the same data as a pass/fail grid, and it shows the thing you will actually experience in production: failure is not a gentle slope. Below the threshold every run dies, above it every run passes, and the threshold depends on the file, so a file that grows 20% overnight crosses it without any code change. That is the 2 a.m. page.

An OutOfMemoryError arrives late, and slowly. The tree runs at 1 GB, 2 GB, 3 GB and 4 GB took 69, 162, 82 and 78 seconds to fail, against 4 seconds at 64 MB. The JVM does not die the moment memory is exhausted; it spends minutes in garbage collection trying to find space and then gives up. If a job “hangs” for a minute and then throws, suspect this before suspecting the network.
How the benchmark was built, and how far to trust it

What was measured. A sampler thread in Scan records the maximum of totalMemory() - freeMemory() every 10 ms and prints it as peakUsed. That figure includes garbage the collector has not yet cleared, so for the streaming rows it overstates the live data. The pass/fail result against a fixed -Xmx is the more reliable number, because the JVM either completed or it did not.

What was not measured. This is one run per cell on one 2-CPU container, not a JMH benchmark. Wall-clock times vary run to run (the streaming row took 8.9 to 12.0 s across heap sizes, which is mostly noise and GC settings), and on a laptop with an SSD and four cores they will differ. The smaller G04 example from the earlier version of this post measured the same three approaches on a 20 MB file; the ordering is the same, but at 20 MB nothing fails, so it cannot show the cliff.

Reproduce it. cd streaming-huge-json && ./scripts/run-all.sh builds, generates the 1 GiB file into the git-ignored target/ directory (it is not committed) and walks the ladder. Allow 10 to 20 minutes, mostly the failing tree runs. --quick skips the big file. The tree row will behave differently on a machine with more than 8 GB of RAM.

The Streaming API: Parsing Gigabyte-Sized JSON Files

The Streaming API processes JSON one token at a time. It never loads the entire document into memory, making it the only practical choice for very large files. The trade-off is verbosity — you must walk the token stream yourself.

Reading a Large JSON Array with JsonParser

Suppose you have a file with millions of log entries and you only need to extract records that match a filter condition. This is the smallest version that works, runnable as G01StreamingParserFilter.java:

// Jackson 3: JsonFactory is in tools.jackson.core.json - note the extra .json,
// it is NOT tools.jackson.core.JsonFactory.
JsonFactory jsonFactory = new JsonFactory();
int errorCount = 0;

// createParser now takes an ObjectReadContext. There is no `throws IOException`
// on this method in Jackson 3 - the exceptions are unchecked.
try (JsonParser parser = jsonFactory.createParser(
        ObjectReadContext.empty(), new File("large-logs.json"))) {

    // Confirm the root is an array
    if (parser.nextToken() != JsonToken.START_ARRAY) {
        throw new IllegalStateException("Expected a JSON array at the root");
    }

    // Walk each element in the array
    while (parser.nextToken() != JsonToken.END_ARRAY) {

        String logLevel = null;
        String logMessage = null;

        // Walk each field inside the current object
        while (parser.nextToken() != JsonToken.END_OBJECT) {
            String fieldName = parser.currentName();   // was getCurrentName()
            parser.nextToken(); // Move to field value

            if ("level".equals(fieldName)) {
                logLevel = parser.getString();         // was getText()
            } else if ("message".equals(fieldName)) {
                logMessage = parser.getString();       // was getText()
            }
            // All other fields are skipped automatically
        }

        if ("ERROR".equals(logLevel)) {
            System.out.println("ERROR: " + logMessage);
            errorCount++;
        }
    }
}
System.out.println("Total errors found: " + errorCount);

Sample input (large-logs.json excerpt):

[
  {"level":"INFO","message":"Application started"},
  {"level":"ERROR","message":"Database connection failed"},
  {"level":"INFO","message":"Retrying connection"}
]

Output (verbatim from docs/output/G01StreamingParserFilter.txt):

ERROR: Database connection failed
Total errors found: 1

Two things to notice for a first read. First, try (JsonParser parser = ...) closes the file for you, and nothing declares throws IOException: in Jackson 3 the exceptions are unchecked, so you can call this from a lambda without wrapping. Second, the loop only ever holds logLevel and logMessage for the record it is on. Those two strings are the entire memory cost of this program, which is why it works on a file of any size.

But this loop has a bug waiting for real data, and it is the most common streaming mistake.

The trap: nested objects break the “until END_OBJECT” loop

The loop above is correct only for flat records. Real log lines have a nested object or array in them (our benchmark records have user and tags). The inner loop stops at the first END_OBJECT it sees, which is now the end of the nested object, so the parser is one level out of step from then on. NestedTrap.java runs the loop above and the fixed version over the same three nested records. Real output, from output/NestedTrap.txt:

expected: 2 ERROR records

-- original loop (flat objects only) --
ERROR: null
guard tripped (inner loop)

-- with skipChildren() --
ERROR: database down
ERROR: disk full
Total errors found: 2

The wrong version printed ERROR: null and then kept going through the wrong tokens. I had to add a loop guard to the demo, because on this input the original loop does not end by itself. The fix is two small changes, shown below from Scan.java: stop the inner loop when the next token is no longer a property name, and call skipChildren() on values you do not need. skipChildren() does nothing for a scalar, and for a START_OBJECT or START_ARRAY it consumes the whole nested structure and leaves you on its matching end token.

static long[] stream(File file) {
    long records = 0, errors = 0, latency = 0;
    try (JsonParser p = new JsonFactory().createParser(ObjectReadContext.empty(), file)) {
        if (p.nextToken() != JsonToken.START_ARRAY) throw new IllegalStateException("expected array");
        while (p.nextToken() == JsonToken.START_OBJECT) {       // one record
            records++;
            String level = null;
            int lat = 0;
            while (p.nextToken() == JsonToken.PROPERTY_NAME) {   // one field of the record
                String name = p.currentName();
                p.nextToken();                                    // move onto the value
                switch (name) {
                    case "level" -> level = p.getString();
                    case "latencyMs" -> lat = p.getIntValue();
                    default -> p.skipChildren();                  // nested user{} / tags[] skipped whole
                }
            }
            if ("ERROR".equals(level)) { errors++; latency += lat; }
        }
    }
    return new long[]{records, errors, latency};
}
Fingerprint of this bug. Counts that are slightly wrong, a field that is null when you can see it in the file, or an infinite loop at the end of the input. If your streaming code works on the sample but not on the real file, check for nested structures first.
Going deeper: why not just use readValueAs for the whole record?

You can, and it is often the right call. Walking the array with JsonParser and binding each element to a record keeps memory flat and removes the manual token handling. It cost about twice the wall-clock time in these runs (19 to 31 s against 9 to 12 s) because every record becomes real objects. The benchmark calls this the hybrid mode:

static long[] hybrid(File file) {
    JsonMapper mapper = JsonMapper.builder().build();
    long records = 0, errors = 0, latency = 0;
    try (JsonParser p = mapper.createParser(file)) {
        if (p.nextToken() != JsonToken.START_ARRAY) throw new IllegalStateException("expected array");
        while (p.nextToken() == JsonToken.START_OBJECT) {
            LogEntry e = p.readValueAs(LogEntry.class);          // binds exactly this object, nothing after it
            records++;
            if ("ERROR".equals(e.level())) { errors++; latency += e.latencyMs(); }
        }
    }
    return new long[]{records, errors, latency};
}

There is a trap on the way. The method you probably reach for first, mapper.readValue(parser, LogEntry.class), is a whole-document call: it verifies that nothing follows the value. In a loop over an array, the next record does follow, and Jackson 3 refuses. The method that binds one value and stops is parser.readValueAs(...). Real output from output/HybridNaive.txt (first three lines; the stack trace continues):

Exception in thread "main" tools.jackson.databind.exc.MismatchedInputException: Trailing token (`JsonToken.START_OBJECT`) found after value (bound as `com.ankurm.jackson3.streaminghuge.Scan$LogEntry`): not allowed as per `DeserializationFeature.FAIL_ON_TRAILING_TOKENS`
 at [Source: REDACTED (`StreamReadFeature.INCLUDE_SOURCE_IN_LOCATION` disabled); byte offset: #258]
	at tools.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:70)

That message names FAIL_ON_TRAILING_TOKENS. Turning the feature off would also silence the check, but readValueAs is the intended tool.

When the file is cut off halfway

Streaming means you act on records before you have seen the end of the file. That is usually the point, but it changes what a truncated upload looks like. TruncatedFile.java feeds both a stream and readTree the same cut-off array. Output from output/TruncatedFile.txt:

input (truncated): [{"id":1,"level":"ERROR"},{"id":2,"level":"INFO"},{"id":3,"level":"ERROR"},

-- streaming --
handled an ERROR record, running total 1
handled an ERROR record, running total 2
exception : tools.jackson.core.exc.StreamReadException
is unchecked: true
first line: Unexpected end-of-input within/between Array entries
records already handled before the exception: 2

-- readTree --
exception : tools.jackson.core.exc.StreamReadException
records handled: 0 (no tree was returned)

The stream had already handled two ERROR records when the exception arrived; readTree returned nothing. Neither is wrong, but you need to decide which you want. If acting on half a file is dangerous (you are charging customers, say), collect results and commit them only after the closing ] has been read. Note also that the exception, tools.jackson.core.exc.StreamReadException, is unchecked (is unchecked: true in the output).

  • Jackson’s default limits (nesting depth 500, string length 100,000,000, no cap on document length) are printed by ReadLimits.java; output in output/ReadLimits.txt. A 1 GiB file is not rejected by default, which is why you must bound it yourself if the source is untrusted. See the Jackson security post.
Output of ReadLimits (default StreamReadConstraints)
maxNestingDepth    = 500
maxStringLength    = 100000000
maxNumberLength    = 1000
maxNameLength      = 50000
maxDocumentLength  = -1  (-1 = unlimited)

Writing JSON with JsonGenerator

JsonGenerator writes tokens directly to an OutputStream or a Writer without building an in-memory object graph first. The version below is the original small example; it is runnable as G02StreamingGenerator.java:

JsonFactory jsonFactory = new JsonFactory();

// Jackson 3: createGenerator takes an ObjectWriteContext.
try (JsonGenerator generator = jsonFactory.createGenerator(
        ObjectWriteContext.empty(), new File("output.json"), JsonEncoding.UTF8)) {

    generator.writeStartArray();

    for (int recordIndex = 0; recordIndex < 1_000_000; recordIndex++) {
        generator.writeStartObject();
        generator.writeNumberProperty("id",     recordIndex);   // was writeNumberField
        generator.writeStringProperty("status", "active");      // was writeStringField
        generator.writeEndObject();
    }

    generator.writeEndArray();
}
// Writes 1 million records to output.json with constant memory usage

Output of G02 (docs/output/G02StreamingGenerator.txt):

records written : 1000000
file size       : 30 MB
elapsed         : 129 ms
heap delta      : 0 MB   <- the document is never held in memory

The same technique produced the 1 GiB benchmark file. GenerateHugeJson.java ran under -Xmx64m, nested objects and arrays included. Its output, from output/GenerateHugeJson.txt (the committed capture is from the second, regeneration run that I compared byte for byte against the first, hence the regen.json file name; a rerun of 8 to 11 seconds is typical here):

wrote target/regen.json : 1,073,741,995 bytes (1.00 GiB), 4,088,325 records, 6,279 ms

One Jackson 3 detail visible in that file: a nested object needs writeName("user") followed by writeStartObject(). The write*Property methods are for scalar values only. The snippet is:

g.writeName("user");
g.writeStartObject();
g.writeNumberProperty("id", rnd.nextInt(5_000_000));
g.writeStringProperty("name", "user" + rnd.nextInt(100_000));
g.writeStringProperty("plan", PLANS[rnd.nextInt(PLANS.length)]);
g.writeEndObject();
g.writeName("tags");
g.writeStartArray();
for (int t = 0; t < 3; t++) g.writeString("tag-" + rnd.nextInt(500));
g.writeEndArray();

From GenerateHugeJson.java.

The Tree Model: Working with Dynamic or Unknown JSON

The Tree Model represents JSON as a navigable JsonNode tree. It is ideal when the JSON schema is not known at compile time, when you need to inspect or transform JSON structure without a matching POJO, or when you want to extract one field without deserialising everything. Everything above says to avoid it for huge files; below about 50 MB it is the friendliest API Jackson has. Runnable as G03TreeModelNavigation.java:

JsonMapper mapper = JsonMapper.builder().build();

String json = "{"
    + "\"orderId\":1001,"
    + "\"customer\":{\"name\":\"Alice\",\"tier\":\"gold\"},"
    + "\"items\":[{\"sku\":\"KB-01\",\"qty\":2},{\"sku\":\"MS-42\",\"qty\":1}]"
    + "}";

// Parse into a tree
JsonNode rootNode = mapper.readTree(json);

// Navigate with path() — never throws NullPointerException even for missing nodes
String customerName = rootNode.path("customer").path("name").asString();
System.out.println("Customer: " + customerName); // Output: Customer: Alice

// Navigate an array
JsonNode itemsArray = rootNode.path("items");
for (JsonNode itemNode : itemsArray) {
    String sku = itemNode.path("sku").asString();
    int    qty = itemNode.path("qty").asInt();
    System.out.println(sku + " x" + qty);
}
// Output:
// KB-01 x2
// MS-42 x1

// Check if a node exists
boolean hasDiscount = rootNode.has("discountCode");
System.out.println("Has discount: " + hasDiscount); // Output: Has discount: false

Verbatim output of G03 (docs/output/G03TreeModelNavigation.txt), which also shows the path() versus get() difference:

Customer: Alice
KB-01 x2
MS-42 x1
Has discount: false
path(missing) :   (class MissingNode)
get(missing)  : null
deep path     : '<default>'
treeToValue   : CustomerRecord[name=Alice, tier=gold]
Correction to the earlier version of this snippet

The earlier version of this post had mismatched quotes in the JSON string literal (it would not compile) and called customer.getName() on a record. The block above escapes the quotes properly, and the next section uses name(). Both fixes are exactly what G03 compiles and runs.

Mixing Tree Model with Data Binding

You can switch between the Tree Model and POJO binding at any node in the tree. This is useful when most of the JSON is dynamic but one known subtree maps to a concrete type (treeToValue line of G03; its output is the last line above, CustomerRecord[name=Alice, tier=gold]):

JsonNode customerNode = rootNode.path("customer");
// Convert this subtree node into a strongly typed POJO
CustomerRecord customer = mapper.treeToValue(customerNode, CustomerRecord.class);
System.out.println(customer.name()); // Output: Alice

Streaming API vs Tree Model vs Data Binding: When to Use Which

Each of Jackson’s three processing modes has a distinct performance and complexity profile. The right choice depends entirely on whether your schema is known, and how large the input is likely to be. The last column is new: what happened on the 1 GiB file.

ApproachBest forMemory usageCode verbosityOn the 1 GiB file (2 CPU, 8 GB)
Data Binding (readValue)Known schema, standard POJO mappingLoads full objectLowFailed at 2,048 MB heap, passed at 3,072 MB
Tree Model (readTree)Dynamic / unknown schema, quick inspectionLoads full treeMediumOutOfMemoryError at every heap up to 4,096 MB
Streaming (JsonParser)Very large files, filtering without full loadConstant (streaming)HighPassed at 32 MB heap, peak 19 MB
Streaming + readValueAs per elementVery large arrays of known recordsConstant (one record)Low to mediumPassed at 32 MB heap, peak 20 MB, about twice the time

Should you stream at all?

Probably not, until you have measured. Streaming code is longer, easier to get subtly wrong (see the nested-object trap) and harder to change. If your files are 5 MB and will stay 5 MB, readValue is correct and simpler, and the rule of thumb from these runs (a record list needed between 2 and 3 times the file size, a tree more than 4 times) says you have a lot of headroom. Reach for streaming when file size is unbounded or comes from outside, when the same service handles many files at once, or when heap is capped by a container limit. If you only need some records of a known type, the per-element readValueAs loop gets you constant memory without hand-written token logic.

The ratios come from one file shape. Records with long strings and few nodes will have a smaller tree overhead; records with many small numbers will have a larger one. Run Scan.java against a sample of your own data before deciding.

See Also

Further reading

AI Prompts for Streaming API and JsonNode

Stream-Parse a Large JSON File

I have a large JSON file containing an array of objects with this structure: [describe or paste one example object]. Using Jackson 3’s JsonParser streaming API, write a method that reads the file token-by-token, extracts only the objects where [describe your filter condition], and collects them into a list — without loading the entire file into memory. Use try-with-resources for the parser and explain each token type encountered in the loop.

What it does: Produces a JsonParser loop that advances through START_ARRAY, START_OBJECT, PROPERTY_NAME, and END_OBJECT tokens, applies the specified filter predicate, and collects matching objects — with inline comments naming each token type so the flow is readable even without prior streaming API knowledge.

When to use it: When processing large export files, analytics dumps, or event logs where loading the full document into memory would exhaust the heap. The streaming approach keeps memory usage constant regardless of file size, making it suitable for files in the hundreds of megabytes or larger. Ask it to use skipChildren() for nested values, or it may reproduce the nested-object bug shown above.

Stream-Write a JSON Array to OutputStream

I have a List of domain objects of this type: [paste class here]. Using Jackson 3’s JsonGenerator, write a method that streams this list to an OutputStream as a JSON array without building the full JSON string in memory first. Use try-with-resources, call writeStartArray and writeEndArray around the loop, and write each object field-by-field. Show how to wire this into a Spring streaming ResponseEntity.

What it does: Creates a try-with-resources JsonGenerator block that emits each object field-by-field using writeStartObject, typed write methods, and writeEndObject, plus a Spring StreamingResponseBody integration example that flushes the response incrementally rather than buffering the full payload.

When to use it: When generating large JSON responses in a streaming REST endpoint, writing ETL output files, or any scenario where backpressure and low memory footprint matter more than code simplicity. Particularly valuable when response size is unpredictable and buffering could cause out-of-memory errors under load.

Navigate Nested JSON with JsonNode

I have this complex nested JSON payload: [paste JSON here]. Using Jackson 3’s JsonNode tree model, show me how to safely navigate to these specific fields: [list the fields]. Use path() instead of get() where a field may be absent. For any array nodes, show iteration with elements(). Where a subtree maps to a known type, show how to convert it with treeToValue(). Explain the difference between path() returning MissingNode and get() returning null.

What it does: Demonstrates safe tree traversal of the provided JSON using path() (returns MissingNode, never null), explains why get() is unsafe for optional fields, shows elements() iteration for array nodes, and demonstrates treeToValue(subtree, MyDto.class) for mixed tree-and-binding workflows where only part of the document maps to a known type.

When to use it: When consuming a heterogeneous or partially-unknown JSON payload — such as a webhook with a variable structure depending on event type — where you need to inspect a few fields dynamically and bind only the known subtrees to typed classes, rather than defining a full POJO for the entire document.

Conclusion

For everyday JSON mapping, stick with data binding — it is concise and safe. Reach for the Tree Model when you need to navigate dynamic or partially-known JSON without creating a POJO for every possible structure. Switch to the Streaming API only when memory is the constraint, such as processing large export files or ingesting event streams. On a real 1 GiB file the difference was 19 MB of heap against a tree that would not fit in 4 GB. Knowing which tool to apply in each scenario is what separates a good Jackson developer from a great one.

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.