Skip to content

API Reference

m4bwav edited this page Sep 30, 2026 · 3 revisions

Everything public is in the assembly JsonPrettyPrinterPlus, in two namespaces: JsonPrettyPrinterPlus for the printer and JsonPrettyPrinterPlus.JsonSerialization for the System.Text.Json helpers. This page describes 3.0.2 (the same API as 3.0.1); members added after 2.0.0 carry the version that introduced them. The same text is in the package's XML documentation, so IntelliSense shows it too.

PrettyPrinterExtensions

A static class with two extension methods on string. This is the one-call API.

Member Returns Notes
PrettyPrintJson(this string unprettyJson) string Formats with JsonPrettyPrintOptions.Default. Reuses one JsonPrettyPrinter per thread, so it is safe to call from anywhere and allocates only the output. Blank input (empty or whitespace) gives an empty string.
PrettyPrintJson(this string unprettyJson, JsonPrettyPrintOptions options) (2.1.1) string The same with your layout. Creates a new printer for each call. Throws ArgumentNullException for null options.

Both throw ArgumentNullException for a null string; the parameter named in the exception is inputString, from the printer underneath. Both throw FormatException for a closing bracket with nothing to close or of the wrong kind (Not a validator).

JsonPrettyPrinter

public sealed class JsonPrettyPrinter. Holds one set of options and one internal engine, and formats any number of documents with them. Not thread-safe: the engine's state is reset at the start of each call and used for its whole length. Sealed since 3.0.

Member Notes
new JsonPrettyPrinter() Uses JsonPrettyPrintOptions.Default.
new JsonPrettyPrinter(JsonPrettyPrintOptions options) (2.1.1) Throws ArgumentNullException for null.
Options (2.1.1) JsonPrettyPrintOptions, read-only. The options this printer writes with.
PrettyPrint(string inputString) Returns the indented text, or an empty string for blank input. Throws ArgumentNullException (parameter inputString) for null.
PrettyPrint(ReadOnlySpan<char> input) (2.1.1) The same for a span, so a slice of a bigger buffer needs no substring.
PrettyPrint(string inputString, TextWriter output) (2.1.1) Writes straight into the writer; blank input writes nothing. Throws ArgumentNullException for a null string (inputString) or writer (output).
PrettyPrint(ReadOnlySpan<char> input, TextWriter output) (2.1.1) The same for a span. Throws ArgumentNullException for a null writer.

All four throw FormatException for a stray or mismatched closing bracket. The string overloads then return nothing; the writer overloads have already written everything up to the bad bracket, because the engine writes as it reads.

The string overloads build the output in a StringBuilder sized at one and a half times the input. Performance and threading has the numbers.

JsonPrettyPrintOptions (2.1.1)

public sealed record JsonPrettyPrintOptions. Immutable: set the properties in an object initializer or with a with expression.

Member Type Default Notes
Default (static) JsonPrettyPrintOptions The instance used when none is given: four spaces, "\n".
IndentSize int 4 Spaces per nesting level. 0 means no indentation. Ignored when UseTabs is true. A negative value throws ArgumentOutOfRangeException when the object is initialised.
UseTabs bool false One tab per level instead of spaces.
NewLine string "\n" Written after {, [ and ,, and before a closing bracket that closes a non-empty scope. Any string is accepted: Environment.NewLine for the 2.x behaviour, " " for one readable line, "" for no breaks at all. Null throws ArgumentNullException.

Because it is a record, two instances with the same values are equal (new JsonPrettyPrintOptions() == JsonPrettyPrintOptions.Default is true) and ToString() prints the three values.

var compact = JsonPrettyPrintOptions.Default with { IndentSize = 2 };
var windows = new JsonPrettyPrintOptions { NewLine = Environment.NewLine };

The init setters work on netstandard2.0 with any compiler from C# 9 on; the package carries the IsExternalInit polyfill. From F#, JsonPrettyPrintOptions(IndentSize = 2) sets them; from PowerShell 7, assign the property after ::new().

JsonExtensions

A static class in JsonPrettyPrinterPlus.JsonSerialization: thin wrappers over System.Text.Json.JsonSerializer that add a prettyPrint switch and default to compact output with property names as declared. Serialisation helpers has the examples.

Member Notes
ToJson(this object? graph) (2.1.1) Compact JSON with the library defaults. null gives the text null.
ToJson(this object? graph, bool prettyPrint) (2.1.1) With prettyPrint: true the result goes through PrettyPrintJson().
ToJson(this object? graph, JsonSerializerOptions? options, bool prettyPrint = false) (2.1.1) Your serializer options; null means the library defaults.
ToJson<T>(this T graph, JsonTypeInfo<T> typeInfo, bool prettyPrint = false) (2.1.1) Source-generated metadata, safe for trimming and native AOT. Throws ArgumentNullException for a null typeInfo.
DeserializeFromJson<T>(this string json) Throws ArgumentNullException for null text and JsonException for text that is not valid JSON for T.
DeserializeFromJson<T>(this string json, JsonSerializerOptions? options) (2.1.1) Your serializer options; null means the library defaults.
DeserializeFromJson<T>(this string json, JsonTypeInfo<T> typeInfo) (2.1.1) Source-generated metadata. Throws ArgumentNullException for null text or typeInfo.

The library defaults are new JsonSerializerOptions { WriteIndented = false }, which is System.Text.Json's own behaviour: property names as declared, dates as ISO 8601, and quotes, apostrophes, <, >, & and every character outside ASCII escaped as \uXXXX.

The overloads without a JsonTypeInfo<T> use reflection and serialise graph as its runtime type, so an object variable holding a Person writes every Person property. On net10.0 they are marked RequiresUnreferencedCode and RequiresDynamicCode: a trimmed or AOT-published app gets warnings IL2026 and IL3050 at each call and should use the JsonTypeInfo<T> overloads instead.

Exceptions

Exception When
ArgumentNullException Null JSON text (parameter inputString, or json for the deserialisers), null options, a null TextWriter (output), a null typeInfo, or null assigned to NewLine (parameter value).
ArgumentOutOfRangeException IndentSize below zero. The message starts IndentSize cannot be negative.
FormatException A closing bracket with nothing open: Unexpected '}' at index 7: there is no open object or array to close. The wrong kind of closing bracket: Unexpected '}' at index 2: expected ']'. The index counts characters from zero in the input as given, whitespace included.
JsonException From DeserializeFromJson, for text System.Text.Json cannot read as a T.
InvalidOperationException From a reflection-based ToJson or DeserializeFromJson in an app where System.Text.Json's reflection is disabled: native AOT, or a .NET 10 file-based app with its default settings.

Nothing else throws. Missing closing brackets, unterminated strings, trailing commas and comments are not errors; Not a validator shows what they produce.

Thread safety

PrettyPrintJson() keeps one printer per thread in a [ThreadStatic] field; PrettyPrintJson(options) creates one per call; both are safe from any thread. A JsonPrettyPrinter you create is not. JsonPrettyPrintOptions is immutable and can be shared. The serialisation helpers share one JsonSerializerOptions, which System.Text.Json makes read-only on first use.

Removed in 3.0

For anyone reading 2.x code: JsonPPStrategyContext, PPScopeState, ICharacterStrategy, the ten strategy classes, the JsonPrettyPrinter(JsonPPStrategyContext) constructor, the public fields IsProcessingVariableAssignment and SpacesPerIndent, and ToJSON() no longer exist. Versions and upgrading maps each to its replacement.

Clone this wiki locally