How it works
JSON parsing has a default grammar, but some tools generate documents containing extensions such as trailing commas. System.Text.Json can be configured to allow selected extensions. That flexibility should be an explicit compatibility decision: accepting a wider grammar changes which documents the application treats as valid input.
JsonDocument is useful when a small importer needs to inspect a document without first declaring a complete object model. It owns the parsed document's storage and should be disposed when inspection is finished. Values obtained from it are tied to that lifetime unless they are copied or cloned appropriately. This lesson keeps every inspection inside a using scope and returns ordinary integers for later output.
Walk through the example. The prepared text contains a trailing comma after the final array element. Parsing with default options throws JsonException, which the sample catches as an expected format rejection. Parsing again with AllowTrailingCommas enabled succeeds. The code then enumerates the numbers and prints their sum while the document is still alive. No parser setting silently changes the arithmetic itself.
Watch the boundary. Permissive parsing is not a repair strategy for arbitrary malformed input. Enabling trailing commas does not permit every non-JSON feature, and it does not validate required properties or numeric ranges. Keep syntax options narrow, inspect value kinds before consuming unexpected documents, and separate parse failures from business-rule failures so support reports can identify the actual boundary that rejected a document.
Practice independently. Define an importer for a small array of integer quantities. Decide whether trailing commas are allowed, then test documents with and without one. Add a wrong value kind, an empty array, and a negative quantity. Record which checks belong to parsing, type inspection, and domain validation. Finally return a plain summary value from the using scope so no JsonElement outlives the document accidentally.
A working example
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
string text = "[1,2,3,]";
try { using var strict = JsonDocument.Parse(text); }
catch (JsonException) { Console.WriteLine("strict:rejected"); }
using (var relaxed = JsonDocument.Parse(text, new JsonDocumentOptions { AllowTrailingCommas = true }))
{
int total = 0;
foreach (var value in relaxed.RootElement.EnumerateArray()) total += value.GetInt32();
Console.WriteLine($"relaxed:{total}");
}
Expected output
strict:rejected relaxed:6
Choose permitted syntax explicitly, and consume document-backed values within their lifetime.