TextureRegion2DJsonConverter.cs 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. using System;
  2. using System.Text.Json;
  3. using System.Text.Json.Serialization;
  4. using MonoGame.Extended.Graphics;
  5. namespace MonoGame.Extended.Serialization.Json;
  6. /// <summary>
  7. /// Converts a <see cref="Texture2DRegion"/> value to or from JSON.
  8. /// </summary>
  9. public class TextureRegion2DJsonConverter : JsonConverter<Texture2DRegion>
  10. {
  11. private readonly ITextureRegionService _textureRegionService;
  12. /// <summary>
  13. /// Initializes a new instance of the <see cref="TextureRegion2DJsonConverter"/> class.
  14. /// </summary>
  15. /// <param name="textureRegionService">The texture region service to use for retrieving texture regions.</param>
  16. /// <exception cref="ArgumentNullException">
  17. /// Thrown if <paramref name="textureRegionService"/> is <see langword="null"/>.
  18. /// </exception>
  19. public TextureRegion2DJsonConverter(ITextureRegionService textureRegionService)
  20. {
  21. ArgumentNullException.ThrowIfNull(textureRegionService);
  22. _textureRegionService = textureRegionService;
  23. }
  24. /// <inheritdoc />
  25. public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Texture2DRegion);
  26. /// <inheritdoc />
  27. public override Texture2DRegion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
  28. {
  29. var regionName = reader.GetString();
  30. return string.IsNullOrEmpty(regionName) ? null : _textureRegionService.GetTextureRegion(regionName);
  31. }
  32. /// <inheritdoc />
  33. /// <exception cref="ArgumentNullException">
  34. /// Throw if <paramref name="writer"/> is <see langword="null"/>.
  35. ///
  36. /// -or-
  37. ///
  38. /// Thrown if <paramref name="value"/> is <see langword="null"/>.
  39. /// </exception>
  40. public override void Write(Utf8JsonWriter writer, Texture2DRegion value, JsonSerializerOptions options)
  41. {
  42. ArgumentNullException.ThrowIfNull(writer);
  43. ArgumentNullException.ThrowIfNull(value);
  44. writer.WriteStringValue(value.Name);
  45. }
  46. }