Skip to content

StreamWriteConstraints

Tatu Saloranta edited this page Aug 25, 2025 · 3 revisions

Jackson core, Processing Limits: StreamWriteConstraints

General

StreamWriteConstraints were added in Jackson 2.16 to provide configurable limits on streaming output.
They act as guards against problematic or maliciously large JSON structures by preventing the generation of "too big" constructs.

Constraints are registered with a TokenStreamFactory (such as JsonFactory). If nothing is explicitly specified, default constraints are used.

Usage

Constraints can be configured in different ways:

// Option 1: (preferred) use builder directly when constructing JsonFactory
JsonFactory f = JsonFactory.builder()
    .streamWriteConstraints(
        StreamWriteConstraints.builder()
            .maxNestingDepth(500) // customize constraint
            .build()
    )
    .build();

// Option 2: (discouraged) override defaults globally (to use with caution!)
StreamWriteConstraints.overrideDefaultStreamWriteConstraints(
    StreamWriteConstraints.builder()
        .maxNestingDepth(200)
        .build()
);

Features

Currently constrained aspects:

Nesting Depth

  • Maximum nesting depth

    • Default: 1000
    • Accessor: getMaxNestingDepth()
    • Builder method: builder().maxNestingDepth(int)
    • Depth is defined as the number of open objects { and arrays [ that have not yet been closed.
    • Setting a negative value throws IllegalArgumentException.
  • Validation helper:

    • Convenience method validateNestingDepth(int depth)
    • Throws StreamConstraintsException if the given depth exceeds the configured maximum.

Default Values

  • DEFAULT_MAX_DEPTH = 1000

You can fetch the defaults with:

StreamWriteConstraints defaults = StreamWriteConstraints.defaults();

Notes

  • Use overrideDefaultStreamWriteConstraints(...) only in application code (never in libraries) to avoid interfering with other Jackson usage.
  • For libraries, configure ObjectMapper or JsonFactory instances individually instead.
Clone this wiki locally