save progress
This commit is contained in:
@@ -75,13 +75,55 @@ public sealed class StableDictionaryConverter<TKey, TValue> : JsonConverter<IDic
|
||||
public override void Write(Utf8JsonWriter writer, IDictionary<TKey, TValue> value, JsonSerializerOptions options)
|
||||
{
|
||||
writer.WriteStartObject();
|
||||
foreach (var kvp in value.OrderBy(x => x.Key?.ToString(), StringComparer.Ordinal))
|
||||
var ordered = value
|
||||
.Select(kvp => new
|
||||
{
|
||||
Key = kvp.Key,
|
||||
Value = kvp.Value,
|
||||
RawKeyString = ConvertKeyToString(kvp.Key)
|
||||
})
|
||||
.Select(kvp => new
|
||||
{
|
||||
kvp.Key,
|
||||
kvp.Value,
|
||||
kvp.RawKeyString,
|
||||
KeyString = ApplyKeyPolicy(kvp.RawKeyString, options)
|
||||
})
|
||||
.OrderBy(kvp => kvp.KeyString, StringComparer.Ordinal)
|
||||
.ThenBy(kvp => kvp.RawKeyString, StringComparer.Ordinal);
|
||||
|
||||
foreach (var kvp in ordered)
|
||||
{
|
||||
writer.WritePropertyName(kvp.Key?.ToString() ?? string.Empty);
|
||||
writer.WritePropertyName(kvp.KeyString);
|
||||
JsonSerializer.Serialize(writer, kvp.Value, options);
|
||||
}
|
||||
writer.WriteEndObject();
|
||||
}
|
||||
|
||||
private static string ConvertKeyToString(TKey key)
|
||||
{
|
||||
if (key is null)
|
||||
{
|
||||
throw new ArgumentException("Dictionary key cannot be null.", nameof(key));
|
||||
}
|
||||
|
||||
return key switch
|
||||
{
|
||||
string s => s,
|
||||
IFormattable formattable => formattable.ToString(null, CultureInfo.InvariantCulture),
|
||||
_ => Convert.ToString(key, CultureInfo.InvariantCulture)
|
||||
} ?? string.Empty;
|
||||
}
|
||||
|
||||
private static string ApplyKeyPolicy(string keyString, JsonSerializerOptions options)
|
||||
{
|
||||
if (options.DictionaryKeyPolicy is not null)
|
||||
{
|
||||
keyString = options.DictionaryKeyPolicy.ConvertName(keyString);
|
||||
}
|
||||
|
||||
return keyString;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -90,7 +132,10 @@ public sealed class StableDictionaryConverter<TKey, TValue> : JsonConverter<IDic
|
||||
public sealed class Iso8601DateTimeConverter : JsonConverter<DateTimeOffset>
|
||||
{
|
||||
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
|
||||
=> DateTimeOffset.Parse(reader.GetString()!, CultureInfo.InvariantCulture);
|
||||
=> DateTimeOffset.Parse(
|
||||
reader.GetString() ?? throw new JsonException("DateTimeOffset value is null."),
|
||||
CultureInfo.InvariantCulture,
|
||||
DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal);
|
||||
|
||||
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options)
|
||||
=> writer.WriteStringValue(value.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture));
|
||||
|
||||
Reference in New Issue
Block a user