ColorJsonConverter.cs 1.4 KB

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