ColorJsonConverter.cs 1.4 KB

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