-
-
Notifications
You must be signed in to change notification settings - Fork 82
/
Copy pathSchemaEnumJsonConverter{T}.cs
87 lines (77 loc) · 2.71 KB
/
SchemaEnumJsonConverter{T}.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
namespace Schema.NET;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.Serialization;
using System.Text.Json;
using System.Text.Json.Serialization;
/// <summary>
/// Converts a Schema enumeration to and from JSON.
/// </summary>
/// <typeparam name="T">The enumeration type to convert.</typeparam>
public class SchemaEnumJsonConverter<T> : JsonConverter<T>
where T : struct, Enum
{
private readonly Dictionary<T, string> valueNameMap = new();
/// <summary>
/// Initializes a new instance of the <see cref="SchemaEnumJsonConverter{T}"/> class.
/// </summary>
public SchemaEnumJsonConverter()
{
var enumType = typeof(T);
var values = Enum.GetValues(enumType);
foreach (var value in values)
{
var enumMember = enumType.GetMember(value!.ToString()!)[0];
var enumMemberAttribute = enumMember.GetCustomAttribute<EnumMemberAttribute>(false);
this.valueNameMap[(T)value] = enumMemberAttribute!.Value!;
}
}
/// <summary>
/// Reads the JSON representation of the enumeration.
/// </summary>
/// <param name="reader">The <see cref="Utf8JsonReader"/> to read from.</param>
/// <param name="typeToConvert">Type of the enumeration.</param>
/// <param name="options">The serializer options.</param>
/// <returns>The enumeration value.</returns>
public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(typeToConvert);
#else
if (typeToConvert is null)
{
throw new ArgumentNullException(nameof(typeToConvert));
}
#endif
var valueString = reader.GetString();
if (EnumHelper.TryParseEnumFromSchemaUri(typeToConvert, valueString, out var result))
{
return (T)result!;
}
return default;
}
/// <summary>
/// Writes the specified enumeration using the JSON writer.
/// </summary>
/// <param name="writer">The JSON writer.</param>
/// <param name="value">The enumeration value.</param>
/// <param name="options">The JSON serializer options.</param>
public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
{
#if NET6_0_OR_GREATER
ArgumentNullException.ThrowIfNull(writer);
ArgumentNullException.ThrowIfNull(options);
#else
if (writer is null)
{
throw new ArgumentNullException(nameof(writer));
}
if (options is null)
{
throw new ArgumentNullException(nameof(options));
}
#endif
writer.WriteStringValue(this.valueNameMap[value]);
}
}