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.
