ColorJsonConverter.cs 1.9 KB

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