using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using MonoGame.Extended.Graphics;
namespace MonoGame.Extended.Serialization.Json;
///
/// Converts a value to or from JSON.
///
public class TextureRegion2DJsonConverter : JsonConverter
{
private readonly ITextureRegionService _textureRegionService;
///
/// Initializes a new instance of the class.
///
/// The texture region service to use for retrieving texture regions.
///
/// Thrown if is .
///
public TextureRegion2DJsonConverter(ITextureRegionService textureRegionService)
{
ArgumentNullException.ThrowIfNull(textureRegionService);
_textureRegionService = textureRegionService;
}
///
public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Texture2DRegion);
///
public override Texture2DRegion Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
var regionName = reader.GetString();
return string.IsNullOrEmpty(regionName) ? null : _textureRegionService.GetTextureRegion(regionName);
}
///
///
/// Throw if is .
///
/// -or-
///
/// Thrown if is .
///
public override void Write(Utf8JsonWriter writer, Texture2DRegion value, JsonSerializerOptions options)
{
ArgumentNullException.ThrowIfNull(writer);
ArgumentNullException.ThrowIfNull(value);
writer.WriteStringValue(value.Name);
}
}