/ src / Ryujinx.Common / Utilities / TypedStringEnumConverter.cs
TypedStringEnumConverter.cs
 1  #nullable enable
 2  using Ryujinx.Common.Logging;
 3  using System;
 4  using System.Text.Json;
 5  using System.Text.Json.Serialization;
 6  
 7  namespace Ryujinx.Common.Utilities
 8  {
 9      /// <summary>
10      /// Specifies that value of <see cref="TEnum"/> will be serialized as string in JSONs
11      /// </summary>
12      /// <remarks>
13      /// Trimming friendly alternative to <see cref="JsonStringEnumConverter"/>.
14      /// Get rid of this converter if dotnet supports similar functionality out of the box.
15      /// </remarks>
16      /// <typeparam name="TEnum">Type of enum to serialize</typeparam>
17      public sealed class TypedStringEnumConverter<TEnum> : JsonConverter<TEnum> where TEnum : struct, Enum
18      {
19          public override TEnum Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
20          {
21              var enumValue = reader.GetString();
22  
23              if (Enum.TryParse(enumValue, out TEnum value))
24              {
25                  return value;
26              }
27  
28              Logger.Warning?.Print(LogClass.Configuration, $"Failed to parse enum value \"{enumValue}\" for {typeof(TEnum)}, using default \"{default(TEnum)}\"");
29              return default;
30          }
31  
32          public override void Write(Utf8JsonWriter writer, TEnum value, JsonSerializerOptions options)
33          {
34              writer.WriteStringValue(value.ToString());
35          }
36      }
37  }