1
+ using System . Runtime . Serialization ;
2
+ using System . Text . Json ;
3
+ using System . Text . Json . Serialization ;
4
+
5
+ namespace AzureOpenAIProxy . ApiApp . Converters ;
6
+
7
+ /// <summary>
8
+ /// This represents the converter entity for <see cref="EnumMemberAttribute"/>.
9
+ /// </summary>
10
+ /// <typeparam name="T">The type of the enum to be converted.</typeparam>
11
+ public class EnumMemberConverter < T > : JsonConverter < T > where T : Enum
12
+ {
13
+ /// <inheritdoc />
14
+ public override T Read ( ref Utf8JsonReader reader , Type typeToConvert , JsonSerializerOptions options )
15
+ {
16
+ var enumText = reader . GetString ( ) ;
17
+
18
+ if ( enumText == null )
19
+ {
20
+ throw new JsonException ( $ "Unable to convert null to Enum \" { typeToConvert } \" .") ;
21
+ }
22
+
23
+ foreach ( var field in typeToConvert . GetFields ( ) )
24
+ {
25
+ var attribute = Attribute . GetCustomAttribute ( field , typeof ( EnumMemberAttribute ) ) as EnumMemberAttribute ;
26
+
27
+ if ( attribute != null && attribute . Value == enumText )
28
+ {
29
+ var value = field . GetValue ( null ) ;
30
+ if ( value != null )
31
+ {
32
+ return ( T ) value ;
33
+ }
34
+ }
35
+ else if ( field . Name == enumText )
36
+ {
37
+ var value = field . GetValue ( null ) ;
38
+ if ( value != null )
39
+ {
40
+ return ( T ) value ;
41
+ }
42
+ }
43
+ }
44
+
45
+ throw new JsonException ( $ "Unable to convert \" { enumText } \" to Enum \" { typeToConvert } \" .") ;
46
+ }
47
+
48
+ /// <inheritdoc />
49
+ public override void Write ( Utf8JsonWriter writer , T value , JsonSerializerOptions options )
50
+ {
51
+ var field = value . GetType ( ) . GetField ( value . ToString ( ) ) ;
52
+
53
+ if ( field != null )
54
+ {
55
+ var attribute = Attribute . GetCustomAttribute ( field , typeof ( EnumMemberAttribute ) ) as EnumMemberAttribute ;
56
+
57
+ if ( attribute != null )
58
+ {
59
+ writer . WriteStringValue ( attribute . Value ) ;
60
+ }
61
+ else
62
+ {
63
+ writer . WriteStringValue ( value . ToString ( ) ) ;
64
+ }
65
+ }
66
+ else
67
+ {
68
+ writer . WriteStringValue ( value . ToString ( ) ) ;
69
+ }
70
+ }
71
+
72
+ }
0 commit comments