ColorJsonConverter.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #nullable disable
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Terminal.Gui.Configuration;
  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. if (ColorStrings.TryParseNamedColor (colorString, out Color namedColor))
  38. {
  39. return namedColor;
  40. }
  41. if (Color.TryParse (colorString, null, out Color parsedColor))
  42. {
  43. return parsedColor;
  44. }
  45. throw new JsonException ($"Unexpected color name: {colorString}.");
  46. }
  47. throw new JsonException ($"Unexpected token when parsing Color: {reader.TokenType}");
  48. }
  49. public override void Write (Utf8JsonWriter writer, Color value, JsonSerializerOptions options)
  50. {
  51. writer.WriteStringValue (value.ToString ());
  52. }
  53. }