Skip to content

Commit af783d6

Browse files
Add JsonSerializer.SerializeAsyncEnumerable for JSONL output
Add SerializeAsyncEnumerable<T> method group to JsonSerializer, symmetric with the existing DeserializeAsyncEnumerable<T>. Default mode (topLevelValues: false) serializes as a JSON array. When topLevelValues is true, produces JSON Lines output with each element as a separate top-level value separated by newlines. The newline format respects JsonSerializerOptions.NewLine for consistency with Utf8JsonWriter indentation settings. Overloads provided for Stream and PipeWriter, with JsonSerializerOptions and JsonTypeInfo<T> variants. topLevelValues is an optional parameter defaulting to false. Co-authored-by: Copilot <[email protected]>
1 parent 6b19ef5 commit af783d6

5 files changed

Lines changed: 357 additions & 0 deletions

File tree

‎src/libraries/System.Text.Json/ref/System.Text.Json.cs‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -356,6 +356,14 @@ public static void Serialize(System.Text.Json.Utf8JsonWriter writer, object? val
356356
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
357357
public static System.Threading.Tasks.Task SerializeAsync(System.IO.Pipelines.PipeWriter utf8Json, object? value, System.Type inputType, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
358358
public static System.Threading.Tasks.Task SerializeAsync(System.IO.Pipelines.PipeWriter utf8Json, object? value, System.Type inputType, System.Text.Json.Serialization.JsonSerializerContext context, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
359+
[System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
360+
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
361+
public static System.Threading.Tasks.Task SerializeAsyncEnumerable<TValue>(System.IO.Stream utf8Json, System.Collections.Generic.IAsyncEnumerable<TValue> value, bool topLevelValues = false, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
362+
public static System.Threading.Tasks.Task SerializeAsyncEnumerable<TValue>(System.IO.Stream utf8Json, System.Collections.Generic.IAsyncEnumerable<TValue> value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo, bool topLevelValues = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
363+
[System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
364+
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]
365+
public static System.Threading.Tasks.Task SerializeAsyncEnumerable<TValue>(System.IO.Pipelines.PipeWriter utf8Json, System.Collections.Generic.IAsyncEnumerable<TValue> value, bool topLevelValues = false, System.Text.Json.JsonSerializerOptions? options = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
366+
public static System.Threading.Tasks.Task SerializeAsyncEnumerable<TValue>(System.IO.Pipelines.PipeWriter utf8Json, System.Collections.Generic.IAsyncEnumerable<TValue> value, System.Text.Json.Serialization.Metadata.JsonTypeInfo<TValue> jsonTypeInfo, bool topLevelValues = false, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; }
359367
public static System.Text.Json.JsonDocument SerializeToDocument(object? value, System.Text.Json.Serialization.Metadata.JsonTypeInfo jsonTypeInfo) { throw null; }
360368
[System.Diagnostics.CodeAnalysis.RequiresDynamicCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed and might need runtime code generation. Use System.Text.Json source generation for native AOT applications.")]
361369
[System.Diagnostics.CodeAnalysis.RequiresUnreferencedCodeAttribute("JSON serialization and deserialization might require types that cannot be statically analyzed. Use the overload that takes a JsonTypeInfo or JsonSerializerContext, or make sure all of the required types are preserved.")]

‎src/libraries/System.Text.Json/src/System/Text/Json/JsonHelpers.cs‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -512,5 +512,16 @@ static int IndexOfFirstTrailingZero(ReadOnlySpan<byte> span)
512512
}
513513
}
514514
}
515+
516+
/// <summary>
517+
/// Returns the UTF-8 byte representation of the newline string configured in the specified <see cref="JsonWriterOptions"/>.
518+
/// </summary>
519+
public static ReadOnlyMemory<byte> GetNewLineBytes(JsonWriterOptions writerOptions)
520+
{
521+
Debug.Assert(writerOptions.NewLine is "\n" or "\r\n");
522+
return writerOptions.NewLine.Length == 2
523+
? "\r\n"u8.ToArray()
524+
: "\n"u8.ToArray();
525+
}
515526
}
516527
}

‎src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Pipe.cs‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System.Collections.Generic;
5+
using System.Diagnostics;
46
using System.Diagnostics.CodeAnalysis;
57
using System.IO.Pipelines;
68
using System.Text.Json.Serialization;
@@ -164,5 +166,117 @@ public static Task SerializeAsync(
164166

165167
return jsonTypeInfo.SerializeAsObjectAsync(utf8Json, value, cancellationToken);
166168
}
169+
170+
/// <summary>
171+
/// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="PipeWriter"/>
172+
/// in a streaming manner.
173+
/// </summary>
174+
/// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
175+
/// <param name="utf8Json">The <see cref="PipeWriter"/> to write to.</param>
176+
/// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
177+
/// <param name="topLevelValues"><see langword="true"/> to serialize as a sequence of newline-separated top-level JSON values (JSON Lines),
178+
/// or <see langword="false"/> to serialize as a single root-level JSON array.</param>
179+
/// <param name="options">Options to control the serialization behavior.</param>
180+
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the write operation.</param>
181+
/// <returns>A task that represents the asynchronous write operation.</returns>
182+
/// <exception cref="ArgumentNullException">
183+
/// <paramref name="utf8Json"/> or <paramref name="value"/> is <see langword="null"/>.
184+
/// </exception>
185+
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
186+
[RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
187+
public static Task SerializeAsyncEnumerable<TValue>(
188+
PipeWriter utf8Json,
189+
IAsyncEnumerable<TValue> value,
190+
bool topLevelValues = false,
191+
JsonSerializerOptions? options = null,
192+
CancellationToken cancellationToken = default)
193+
{
194+
ArgumentNullException.ThrowIfNull(utf8Json);
195+
ArgumentNullException.ThrowIfNull(value);
196+
197+
JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
198+
return topLevelValues
199+
? SerializeAsyncEnumerableAsTopLevelValues(utf8Json, value, jsonTypeInfo, cancellationToken)
200+
: SerializeAsync<IAsyncEnumerable<TValue>>(utf8Json, value, options, cancellationToken);
201+
}
202+
203+
/// <summary>
204+
/// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="PipeWriter"/>
205+
/// in a streaming manner.
206+
/// </summary>
207+
/// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
208+
/// <param name="utf8Json">The <see cref="PipeWriter"/> to write to.</param>
209+
/// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
210+
/// <param name="jsonTypeInfo">Metadata about the type of elements to serialize.</param>
211+
/// <param name="topLevelValues"><see langword="true"/> to serialize as a sequence of newline-separated top-level JSON values (JSON Lines),
212+
/// or <see langword="false"/> to serialize as a single root-level JSON array.</param>
213+
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the write operation.</param>
214+
/// <returns>A task that represents the asynchronous write operation.</returns>
215+
/// <exception cref="ArgumentNullException">
216+
/// <paramref name="utf8Json"/>, <paramref name="value"/>, or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
217+
/// </exception>
218+
public static Task SerializeAsyncEnumerable<TValue>(
219+
PipeWriter utf8Json,
220+
IAsyncEnumerable<TValue> value,
221+
JsonTypeInfo<TValue> jsonTypeInfo,
222+
bool topLevelValues = false,
223+
CancellationToken cancellationToken = default)
224+
{
225+
ArgumentNullException.ThrowIfNull(utf8Json);
226+
ArgumentNullException.ThrowIfNull(value);
227+
ArgumentNullException.ThrowIfNull(jsonTypeInfo);
228+
229+
jsonTypeInfo.EnsureConfigured();
230+
if (topLevelValues)
231+
{
232+
return SerializeAsyncEnumerableAsTopLevelValues(utf8Json, value, jsonTypeInfo, cancellationToken);
233+
}
234+
235+
JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = (JsonTypeInfo<IAsyncEnumerable<TValue>>)jsonTypeInfo.Options.GetTypeInfo(typeof(IAsyncEnumerable<TValue>));
236+
return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
237+
}
238+
239+
private static async Task SerializeAsyncEnumerableAsTopLevelValues<TValue>(
240+
PipeWriter utf8Json,
241+
IAsyncEnumerable<TValue> value,
242+
JsonTypeInfo<TValue> jsonTypeInfo,
243+
CancellationToken cancellationToken)
244+
{
245+
Debug.Assert(jsonTypeInfo.IsConfigured);
246+
247+
JsonWriterOptions writerOptions = jsonTypeInfo.Options.GetWriterOptions();
248+
ReadOnlyMemory<byte> newLine = JsonHelpers.GetNewLineBytes(writerOptions);
249+
250+
using var writer = new Utf8JsonWriter(utf8Json, writerOptions);
251+
252+
bool first = true;
253+
await foreach (TValue item in value.WithCancellation(cancellationToken).ConfigureAwait(false))
254+
{
255+
if (!first)
256+
{
257+
writer.Reset(utf8Json);
258+
}
259+
260+
first = false;
261+
jsonTypeInfo.Serialize(writer, item);
262+
263+
ReadOnlyMemory<byte> nl = newLine;
264+
Memory<byte> memory = utf8Json.GetMemory(nl.Length);
265+
nl.CopyTo(memory);
266+
utf8Json.Advance(nl.Length);
267+
268+
FlushResult result = await utf8Json.FlushAsync(cancellationToken).ConfigureAwait(false);
269+
270+
if (result.IsCanceled)
271+
{
272+
ThrowHelper.ThrowOperationCanceledException_PipeWriteCanceled();
273+
}
274+
275+
if (result.IsCompleted)
276+
{
277+
break;
278+
}
279+
}
280+
}
167281
}
168282
}

‎src/libraries/System.Text.Json/src/System/Text/Json/Serialization/JsonSerializer.Write.Stream.cs‎

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// Licensed to the .NET Foundation under one or more agreements.
22
// The .NET Foundation licenses this file to you under the MIT license.
33

4+
using System.Collections.Generic;
5+
using System.Diagnostics;
46
using System.Diagnostics.CodeAnalysis;
57
using System.IO;
68
using System.Text.Json.Serialization;
@@ -306,5 +308,108 @@ public static void Serialize(
306308
JsonTypeInfo jsonTypeInfo = GetTypeInfo(context, inputType);
307309
jsonTypeInfo.SerializeAsObject(utf8Json, value);
308310
}
311+
312+
/// <summary>
313+
/// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="System.IO.Stream"/>
314+
/// in a streaming manner.
315+
/// </summary>
316+
/// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
317+
/// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
318+
/// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
319+
/// <param name="topLevelValues"><see langword="true"/> to serialize as a sequence of newline-separated top-level JSON values (JSON Lines),
320+
/// or <see langword="false"/> to serialize as a single root-level JSON array.</param>
321+
/// <param name="options">Options to control the serialization behavior.</param>
322+
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the write operation.</param>
323+
/// <returns>A task that represents the asynchronous write operation.</returns>
324+
/// <exception cref="ArgumentNullException">
325+
/// <paramref name="utf8Json"/> or <paramref name="value"/> is <see langword="null"/>.
326+
/// </exception>
327+
[RequiresUnreferencedCode(SerializationUnreferencedCodeMessage)]
328+
[RequiresDynamicCode(SerializationRequiresDynamicCodeMessage)]
329+
public static Task SerializeAsyncEnumerable<TValue>(
330+
Stream utf8Json,
331+
IAsyncEnumerable<TValue> value,
332+
bool topLevelValues = false,
333+
JsonSerializerOptions? options = null,
334+
CancellationToken cancellationToken = default)
335+
{
336+
ArgumentNullException.ThrowIfNull(utf8Json);
337+
ArgumentNullException.ThrowIfNull(value);
338+
339+
JsonTypeInfo<TValue> jsonTypeInfo = GetTypeInfo<TValue>(options);
340+
return topLevelValues
341+
? SerializeAsyncEnumerableAsTopLevelValues(utf8Json, value, jsonTypeInfo, cancellationToken)
342+
: SerializeAsync<IAsyncEnumerable<TValue>>(utf8Json, value, options, cancellationToken);
343+
}
344+
345+
/// <summary>
346+
/// Serializes each element of an <see cref="IAsyncEnumerable{TValue}"/> to the <see cref="System.IO.Stream"/>
347+
/// in a streaming manner.
348+
/// </summary>
349+
/// <typeparam name="TValue">The type of elements in the sequence to serialize.</typeparam>
350+
/// <param name="utf8Json">The UTF-8 <see cref="System.IO.Stream"/> to write to.</param>
351+
/// <param name="value">The <see cref="IAsyncEnumerable{T}"/> sequence to serialize.</param>
352+
/// <param name="jsonTypeInfo">Metadata about the type of elements to serialize.</param>
353+
/// <param name="topLevelValues"><see langword="true"/> to serialize as a sequence of newline-separated top-level JSON values (JSON Lines),
354+
/// or <see langword="false"/> to serialize as a single root-level JSON array.</param>
355+
/// <param name="cancellationToken">The <see cref="System.Threading.CancellationToken"/> that can be used to cancel the write operation.</param>
356+
/// <returns>A task that represents the asynchronous write operation.</returns>
357+
/// <exception cref="ArgumentNullException">
358+
/// <paramref name="utf8Json"/>, <paramref name="value"/>, or <paramref name="jsonTypeInfo"/> is <see langword="null"/>.
359+
/// </exception>
360+
public static Task SerializeAsyncEnumerable<TValue>(
361+
Stream utf8Json,
362+
IAsyncEnumerable<TValue> value,
363+
JsonTypeInfo<TValue> jsonTypeInfo,
364+
bool topLevelValues = false,
365+
CancellationToken cancellationToken = default)
366+
{
367+
ArgumentNullException.ThrowIfNull(utf8Json);
368+
ArgumentNullException.ThrowIfNull(value);
369+
ArgumentNullException.ThrowIfNull(jsonTypeInfo);
370+
371+
jsonTypeInfo.EnsureConfigured();
372+
if (topLevelValues)
373+
{
374+
return SerializeAsyncEnumerableAsTopLevelValues(utf8Json, value, jsonTypeInfo, cancellationToken);
375+
}
376+
377+
// Array mode: serialize the IAsyncEnumerable<T> as a JSON array using existing infrastructure.
378+
JsonTypeInfo<IAsyncEnumerable<TValue>> collectionTypeInfo = (JsonTypeInfo<IAsyncEnumerable<TValue>>)jsonTypeInfo.Options.GetTypeInfo(typeof(IAsyncEnumerable<TValue>));
379+
return collectionTypeInfo.SerializeAsync(utf8Json, value, cancellationToken);
380+
}
381+
382+
private static async Task SerializeAsyncEnumerableAsTopLevelValues<TValue>(
383+
Stream utf8Json,
384+
IAsyncEnumerable<TValue> value,
385+
JsonTypeInfo<TValue> jsonTypeInfo,
386+
CancellationToken cancellationToken)
387+
{
388+
Debug.Assert(jsonTypeInfo.IsConfigured);
389+
390+
JsonWriterOptions writerOptions = jsonTypeInfo.Options.GetWriterOptions();
391+
ReadOnlyMemory<byte> newLine = JsonHelpers.GetNewLineBytes(writerOptions);
392+
393+
using var bufferWriter = new PooledByteBufferWriter(jsonTypeInfo.Options.DefaultBufferSize, utf8Json);
394+
using var writer = new Utf8JsonWriter(bufferWriter, writerOptions);
395+
396+
bool first = true;
397+
await foreach (TValue item in value.WithCancellation(cancellationToken).ConfigureAwait(false))
398+
{
399+
if (!first)
400+
{
401+
writer.Reset(bufferWriter);
402+
}
403+
404+
first = false;
405+
jsonTypeInfo.Serialize(writer, item);
406+
407+
ReadOnlySpan<byte> nl = newLine.Span;
408+
Span<byte> dest = bufferWriter.GetSpan(nl.Length);
409+
nl.CopyTo(dest);
410+
bufferWriter.Advance(nl.Length);
411+
await bufferWriter.FlushAsync(cancellationToken).ConfigureAwait(false);
412+
}
413+
}
309414
}
310415
}

0 commit comments

Comments
 (0)