38 lines
1.1 KiB
C#
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);
|
|
}
|