48 lines
1.7 KiB
C#
48 lines
1.7 KiB
C#
using System.Text;
|
|
using System.Text.Json;
|
|
|
|
namespace StellaOps.Canonical.Json;
|
|
|
|
/// <summary>
|
|
/// Canonical JSON serialization with deterministic hashing.
|
|
/// Produces bit-identical output across environments for proof replay.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Key guarantees:
|
|
/// <list type="bullet">
|
|
/// <item>Object keys are sorted alphabetically (Ordinal comparison)</item>
|
|
/// <item>No whitespace or formatting variations</item>
|
|
/// <item>Consistent number formatting</item>
|
|
/// <item>UTF-8 encoding without BOM</item>
|
|
/// </list>
|
|
/// </remarks>
|
|
public static partial class CanonJson
|
|
{
|
|
/// <summary>
|
|
/// Serializes an object to a canonical JSON string.
|
|
/// Object keys are recursively sorted using Ordinal comparison.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type to serialize.</typeparam>
|
|
/// <param name="obj">The object to serialize.</param>
|
|
/// <returns>Canonical JSON string.</returns>
|
|
public static string Serialize<T>(T obj)
|
|
{
|
|
var bytes = Canonicalize(obj);
|
|
return Encoding.UTF8.GetString(bytes);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Serializes an object to a canonical JSON string using custom serializer options.
|
|
/// Object keys are recursively sorted using Ordinal comparison.
|
|
/// </summary>
|
|
/// <typeparam name="T">The type to serialize.</typeparam>
|
|
/// <param name="obj">The object to serialize.</param>
|
|
/// <param name="options">JSON serializer options to use for initial serialization.</param>
|
|
/// <returns>Canonical JSON string.</returns>
|
|
public static string Serialize<T>(T obj, JsonSerializerOptions options)
|
|
{
|
|
var bytes = Canonicalize(obj, options);
|
|
return Encoding.UTF8.GetString(bytes);
|
|
}
|
|
}
|