Path: redb-route/redb.Route/Expressions/Tokenizers/JsonArrayTokenizer.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route/Expressions/Tokenizers/JsonArrayTokenizer.cs ---- using System.Runtime.CompilerServices; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; namespace redb.Route.Expressions.Tokenizers; /// /// Splits a JSON array body into individual elements, each as its JSON text. /// JSON text (, , byte[]) is read with /// ; any other body is taken as jpath takes it (a System.Text.Json tree, /// an array such as the object[] a jpath returns, or a POCO). /// internal static class JsonArrayTokenizer { // Element text as close to the source as the tree allows: non-ASCII stays as written, not \u-escaped. private static readonly JsonSerializerOptions ElementText = new() { Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, }; // C# member names, as jpath serializes a POCO body. private static readonly JsonSerializerOptions PocoOptions = new(); /// Tokenizes a JSON array body into individual raw-text elements. /// Exchange body: JSON text, a JSON tree, a CLR array or collection, or a POCO. /// Cancellation token. internal static async IAsyncEnumerable Tokenize( object? body, [EnumeratorCancellation] CancellationToken ct = default) { if (body is not (Stream or byte[] or string)) { if (body is null) throw new InvalidOperationException("SplitJsonArray: the body is null."); if (JsonPathValues.ToNode(body, default, PocoOptions) is not JsonArray array) throw new InvalidOperationException("SplitJsonArray: body is not a JSON array."); foreach (var element in array) { ct.ThrowIfCancellationRequested(); yield return element is null ? "null" : element.ToJsonString(ElementText); } yield break; } var stream = body switch { Stream s => s, byte[] b => new MemoryStream(b, writable: false), _ => new MemoryStream(Encoding.UTF8.GetBytes((string)body)), }; var ownsStream = body is not Stream; try { await foreach (var element in ReadArrayElementsAsync(stream, ct).ConfigureAwait(false)) { yield return element; } } finally { if (ownsStream) await stream.DisposeAsync().ConfigureAwait(false); } } private static async IAsyncEnumerable ReadArrayElementsAsync( Stream stream, [EnumeratorCancellation] CancellationToken ct) { using var doc = await JsonDocument.ParseAsync(stream, cancellationToken: ct) .ConfigureAwait(false); if (doc.RootElement.ValueKind != JsonValueKind.Array) throw new InvalidOperationException("SplitJsonArray: body is not a JSON array."); foreach (var element in doc.RootElement.EnumerateArray()) { ct.ThrowIfCancellationRequested(); yield return element.GetRawText(); } } }