add json converter for MIMEType

This commit is contained in:
uwaa 2024-11-07 09:55:51 +00:00
parent d94fa95162
commit c6d99ea9be

View file

@ -1,8 +1,12 @@
namespace Uwaa.HTTP;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Uwaa.HTTP;
/// <summary>
/// Represents a Multipurpose Internet Mail Extensions type, which indicates the nature and format of a document/file/chunk of data.
/// </summary>
[JsonConverter(typeof(MIMETypeConverter))]
public readonly record struct MIMEType
{
public static explicit operator string(MIMEType type) => type.ToString();
@ -73,3 +77,22 @@ public readonly record struct MIMEType
/// </summary>
public override readonly string ToString() => $"{Type ?? "*"}/{Subtype ?? "*"}";
}
class MIMETypeConverter : JsonConverter<MIMEType>
{
public sealed override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(MIMEType);
public override MIMEType Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string? str = reader.GetString();
if (str == null)
throw new JsonException("Cannot read MIME type");
return new MIMEType(str);
}
public override void Write(Utf8JsonWriter writer, MIMEType status, JsonSerializerOptions options)
{
writer.WriteStringValue(status.ToString());
}
}