[JsonConverter(typeof(EnumJsonConverter<DocumentStatus>))]
public enum DocumentStatus
{
None = 0,
Rejected = 1,
Approved = 2,
Published = 3,
}
public class EnumJsonConverter<T> : JsonConverter<T> where T : struct, Enum
{
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
string value = reader.GetString();
if (Enum.TryParse(value, out T result))
{
return result;
}
throw new ArgumentException($"Invalid {typeof(T).Name} value");
}
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString());
}
}