Skip to content

Commit

Permalink
move to HandleDictionaryItem
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp committed Nov 10, 2024
1 parent e0defd9 commit d89cddf
Showing 1 changed file with 22 additions and 16 deletions.
38 changes: 22 additions & 16 deletions src/Verify/Serialization/CustomContractResolver_Dictionary.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
protected override JsonDictionaryContract CreateDictionaryContract(Type objectType)
{
var contract = base.CreateDictionaryContract(objectType);
contract.DictionaryKeyResolver = (_, name, original) => ResolveDictionaryKey(name, original);
if (settings.SortDictionaries)
{
contract.OrderByKey = true;
Expand All @@ -28,6 +27,11 @@ KeyValueInterceptResult HandleDictionaryItem(JsonWriter writer, object key, obje
return ToInterceptKeyValueResult(scrubOrIgnore.Value);
}

if (TryConvertDictionaryKey(key, out var resultKey))
{
return KeyValueInterceptResult.ReplaceKey(resultKey);
}

return KeyValueInterceptResult.Default;
}

Expand All @@ -41,67 +45,69 @@ static KeyValueInterceptResult ToInterceptKeyValueResult(ScrubOrIgnore scrubOrIg
return KeyValueInterceptResult.ReplaceValue("{Scrubbed}");
}

string ResolveDictionaryKey(string name, object original)
bool TryConvertDictionaryKey(object original, [NotNullWhen(true)] out string? result)
{
var counter = Counter.Current;

#if NET6_0_OR_GREATER

if (original is Date date)
{
if (settings.TryConvert(counter, date, out var result))
if (settings.TryConvert(counter, date, out result))
{
return result;
return true;
}
}

if (original is Time time)
{
if (settings.TryConvert(counter, time, out var result))
if (settings.TryConvert(counter, time, out result))
{
return result;
return true;
}
}

#endif

if (original is Guid guid)
{
if (settings.TryConvert(counter, guid, out var result))
if (settings.TryConvert(counter, guid, out result))
{
return result;
return true;
}
}

if (original is string stringValue)
{
if (settings.TryParseConvert(counter, stringValue.AsSpan(), out var result))
if (settings.TryParseConvert(counter, stringValue.AsSpan(), out result))
{
return result;
return true;
}
}

if (original is DateTime dateTime)
{
if (settings.TryConvert(counter, dateTime, out var result))
if (settings.TryConvert(counter, dateTime, out result))
{
return result;
return true;
}
}

if (original is DateTimeOffset dateTimeOffset)
{
if (settings.TryConvert(counter, dateTimeOffset, out var result))
if (settings.TryConvert(counter, dateTimeOffset, out result))
{
return result;
return true;
}
}

if (original is Type type)
{
return type.SimpleName();
result = type.SimpleName();
return true;
}

return name;
result = null;
return false;
}
}

0 comments on commit d89cddf

Please sign in to comment.