add json converter for MIMEType
This commit is contained in:
parent
d94fa95162
commit
c6d99ea9be
1 changed files with 24 additions and 1 deletions
|
@ -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());
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue