TrueColorJsonConverter.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. namespace Terminal.Gui {
  5. /// <summary>
  6. /// <see cref="JsonConverter{T}"/> for <see cref="TrueColor"/>.
  7. /// </summary>
  8. internal class TrueColorJsonConverter : JsonConverter<TrueColor> {
  9. private static TrueColorJsonConverter instance;
  10. /// <summary>
  11. /// Singleton
  12. /// </summary>
  13. public static TrueColorJsonConverter Instance {
  14. get {
  15. if (instance == null) {
  16. instance = new TrueColorJsonConverter ();
  17. }
  18. return instance;
  19. }
  20. }
  21. public override TrueColor Read (ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  22. {
  23. // Check if the value is a string
  24. if (reader.TokenType == JsonTokenType.String) {
  25. // Get the color string
  26. var colorString = reader.GetString ();
  27. if (!TrueColor.TryParse (colorString, out TrueColor? trueColor)) {
  28. throw new JsonException ($"Invalid TrueColor: '{colorString}'");
  29. }
  30. return trueColor.Value;
  31. } else {
  32. throw new JsonException ($"Unexpected token when parsing TrueColor: {reader.TokenType}");
  33. }
  34. }
  35. public override void Write (Utf8JsonWriter writer, TrueColor value, JsonSerializerOptions options)
  36. {
  37. writer.WriteStringValue (value.ToString ());
  38. }
  39. }
  40. }