ColorJsonConverter.cs 1.6 KB

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