ColorJsonConverter.cs 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System.Text.Json;
  2. using System.Text.Json.Serialization;
  3. namespace Terminal.Gui;
  4. /// <summary>Json converter for the <see cref="Color"/> class.</summary>
  5. internal class ColorJsonConverter : JsonConverter<Color>
  6. {
  7. private static ColorJsonConverter _instance;
  8. /// <summary>Singleton</summary>
  9. public static ColorJsonConverter Instance
  10. {
  11. get
  12. {
  13. if (_instance is null)
  14. {
  15. _instance = new ColorJsonConverter ();
  16. }
  17. return _instance;
  18. }
  19. }
  20. public override Color Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  21. {
  22. // Check if the value is a string
  23. if (reader.TokenType == JsonTokenType.String)
  24. {
  25. // Get the color string
  26. ReadOnlySpan<char> colorString = reader.GetString ();
  27. // Check if the color string is a color name
  28. if (Enum.TryParse (colorString, true, out ColorName color))
  29. {
  30. // Return the parsed color
  31. return new Color (in color);
  32. }
  33. if (Color.TryParse (colorString, null, out Color parsedColor))
  34. {
  35. return parsedColor;
  36. }
  37. throw new JsonException ($"Unexpected color name: {colorString}.");
  38. }
  39. throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
  40. }
  41. public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options) { writer.WriteStringValue (value.ToString ()); }
  42. }