liveBook · Manning

JsonDocument

As explained in .NET in Action, Second Edition

JsonDocument is a .NET type that provides read-only, in-memory access to the structure and values of a JSON document.

JsonDocument provides read-only, in-memory access to a complete JSON document through the DOM model. Parse a stream, inspect RootElement, enumerate arrays, and retrieve values with GetProperty and GetString. section 4.2.1

Use JsonDocument when a stream-based JSON transformation needs structural inspection:

  • Parse the input stream with JsonDocument.Parse and dispose the document with using. section 4.2.1
  • Traverse the root array with RootElement.EnumerateArray and filter objects by a property such as type. section 4.2.1
  • Send selected elements directly to Utf8JsonWriter with WriteTo, or construct new objects when output should contain only chosen properties. section 4.2.2
  • Prefer serialization when the JSON schema is known and the DOM approach would add unnecessary code. section 4.2.2

Filtering jokes by category

Parse a jokes array, read each object's type property, and write matching elements to an indented JSON array. Utf8JsonWriter supplies commas, brackets, and valid JSON formatting.

How .NET in Action, Second Edition covers it

How deep it goes
Explains whole-document parsing, element traversal, property access, disposal, and output writing, while deferring schema-based serialization as simpler.
Examples
Demonstrates filtering programmer jokes by type and emitting either complete objects or only setup and punchline properties.
What it assumes
Assumes familiarity with JSON arrays, object properties, .NET streams, and C# using declarations.
What you can do after
Apply JsonDocument and Utf8JsonWriter to filter JSON streams and produce well-formed transformed output.
How it connects
Connects JSON DOM traversal with streams, Utf8JsonWriter, and JSON serialization.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.