ColorJsonConverter.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System.Text.Json;
  2. using System.Text.Json.Serialization;
  3. using ColorHelper;
  4. namespace Terminal.Gui;
  5. /// <summary>
  6. /// Json converter for the <see cref="Color"/> class.
  7. /// <para>
  8. /// Serialization outputs a string with the color name if the color matches a name in <see cref="ColorStrings"/>
  9. /// or the "#RRGGBB" hexadecimal representation (e.g. "#FF0000" for red).
  10. /// </para>
  11. /// <para>
  12. /// Deserialization formats supported are "#RGB", "#RRGGBB", "#ARGB", "#AARRGGBB", "rgb(r,g,b)",
  13. /// "rgb(r,g,b,a)", "rgba(r,g,b)", "rgba(r,g,b,a)", or any W3C color name.</para>
  14. /// </summary>
  15. internal class ColorJsonConverter : JsonConverter<Color>
  16. {
  17. private static ColorJsonConverter _instance;
  18. /// <summary>Singleton</summary>
  19. public static ColorJsonConverter Instance
  20. {
  21. get
  22. {
  23. if (_instance is null)
  24. {
  25. _instance = new ();
  26. }
  27. return _instance;
  28. }
  29. }
  30. public override Color Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  31. {
  32. // Check if the value is a string
  33. if (reader.TokenType == JsonTokenType.String)
  34. {
  35. // Get the color string
  36. ReadOnlySpan<char> colorString = reader.GetString ();
  37. // Check if the color string is a color name
  38. if (ColorStrings.TryParseW3CColorName (colorString.ToString (), out Color color1))
  39. {
  40. // Return the parsed color
  41. return new (color1);
  42. }
  43. if (Color.TryParse (colorString, null, out Color parsedColor))
  44. {
  45. return parsedColor;
  46. }
  47. throw new JsonException ($"Unexpected color name: {colorString}.");
  48. }
  49. throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
  50. }
  51. public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
  52. {
  53. writer.WriteStringValue (value.ToString ());
  54. }
  55. }