TypedStringEnumConverter.cs 1.1 KB

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