The Document Object Model (DOM) parses an entire JSON document into an in-memory object representation. In .NET, JsonDocument provides this approach, analogous to XmlDocument for XML, making the document available for inspection and traversal after parsing. section 4.2.1
A typical workflow supplies a readable stream to JsonDocument.Parse, starts at RootElement, enumerates the document’s array, and reads properties such as type with GetProperty and GetString. Filtering can then compare values without manually scanning raw text. section 4.2.1
Dispose the JsonDocument when processing finishes. Use using for deterministic cleanup, while treating streams passed into a method carefully: JsonDocument.Parse does not close its input stream, and a caller may need to continue using it. section 4.2.1
Finding jokes by category
Parse a jokes JSON stream, enumerate the root array, read each object's type property, and write matching jokes to a UTF-8 output stream. The output can target a file or standard output. section 4.2.1
Listing 4.21 Reading the JSON stream and finding jokes by category
using System.Text; #1
using System.Text.Json;
static void FinddWithJsonDom(
Stream inStream,
Stream outStream,
string category)
{
using var writer = new StreamWriter(outStream, #2
Encoding.UTF8, #3
leaveOpen: true); #4
using var jsonDoc = #5
JsonDocument.Parse(inStream); #6
foreach (var jokeElement in jsonDoc #7
.RootElement.EnumerateArray()) #8
{
string? type = jokeElement
.GetProperty("type") #9
.GetString(); #10
if (string.Equals(category, type, #11
StringComparison.OrdinalIgnoreCase)) #12
{
writer.WriteLine(jokeElement.GetRawText()); #13
}
}
}
Use the focused listing to trace stream parsing, JsonDocument lifetime, root-array enumeration, property extraction, and case-insensitive category matching. section 4.2.1







