Skip to content

Commit

Permalink
Add TryGetJsonSerializerOptions extension method (#124)
Browse files Browse the repository at this point in the history
Add `TryGetJsonSerializerOptions` extension method.
  • Loading branch information
flobernd authored Oct 16, 2024
1 parent e790d5e commit 28a141f
Showing 1 changed file with 23 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.IO;
using System.Text.Json;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Text.Json.Nodes;

Expand Down Expand Up @@ -631,4 +632,26 @@ public static void Serialize(

return serializer.Deserialize(type, ms);
}

/// <summary>
/// Extension method that tries to obtain the <see cref="JsonSerializerOptions"/> for <see cref="SystemTextJsonSerializer"/> based
/// <paramref name="serializer"/> implementations.
/// </summary>
/// <param name="serializer"><inheritdoc cref="Serializer" path="/summary"/></param>
/// <param name="options">Receives the <see cref="JsonSerializerOptions"/>.</param>
/// <param name="formatting"><inheritdoc cref="SerializationFormatting" path="/summary"/></param>
public static bool TryGetJsonSerializerOptions(
this Serializer serializer,
[NotNullWhen(true)] out JsonSerializerOptions? options,
SerializationFormatting formatting = SerializationFormatting.None)
{
if (serializer is SystemTextJsonSerializer stjSerializer)
{
options = stjSerializer.GetJsonSerializerOptions(formatting);
return true;
}

options = null;
return false;
}
}

0 comments on commit 28a141f

Please sign in to comment.