Files
Rendezvous/src/FinalFactory.Rendezvous.Contracts/Identifiers/StringIdentifierJsonConverter.cs
T
KyuubiYoru 69c8b2d2bc
quality-gate / quality (push) Successful in 51s
feat: freeze v1 transport contracts (#4)
Closes #4
2026-07-16 04:52:38 +02:00

38 lines
1.1 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
namespace FinalFactory.Rendezvous.Contracts;
internal abstract class StringIdentifierJsonConverter<TIdentifier> : JsonConverter<TIdentifier>
{
public sealed override TIdentifier Read(
ref Utf8JsonReader reader,
Type typeToConvert,
JsonSerializerOptions options)
{
if (reader.TokenType != JsonTokenType.String)
{
throw new JsonException($"{typeof(TIdentifier).Name} must be a JSON string.");
}
string value = reader.GetString() ?? string.Empty;
try
{
return Parse(value);
}
catch (Exception exception) when (exception is ArgumentException or FormatException)
{
throw new JsonException($"Invalid {typeof(TIdentifier).Name}.", exception);
}
}
public sealed override void Write(
Utf8JsonWriter writer,
TIdentifier value,
JsonSerializerOptions options) => writer.WriteStringValue(Format(value));
protected abstract TIdentifier Parse(string value);
protected abstract string Format(TIdentifier value);
}