66 lines
1.5 KiB
C#
66 lines
1.5 KiB
C#
using Godot;
|
|
using System.Text.Json.Serialization;
|
|
|
|
using System.Text.Json;
|
|
|
|
/// <summary>Basis JSON converter.</summary>
|
|
public class Texture2DConverter : JsonConverter<Texture2D>
|
|
{
|
|
/// <inheritdoc />
|
|
public override bool CanConvert(Type typeToConvert) =>
|
|
typeToConvert == typeof(Texture2D);
|
|
|
|
/// <inheritdoc />
|
|
public override Texture2D Read(
|
|
ref Utf8JsonReader reader,
|
|
Type typeToConvert,
|
|
JsonSerializerOptions options)
|
|
{
|
|
var texture2D = new Texture2D();
|
|
|
|
while (reader.Read())
|
|
{
|
|
if (reader.TokenType == JsonTokenType.EndObject)
|
|
{
|
|
return texture2D;
|
|
}
|
|
|
|
if (reader.TokenType != JsonTokenType.PropertyName)
|
|
{
|
|
continue;
|
|
}
|
|
|
|
var propertyName = reader.GetString();
|
|
reader.Read();
|
|
|
|
switch (propertyName)
|
|
{
|
|
case "resource_path":
|
|
var resourcePath = JsonSerializer.Deserialize<string>(ref reader, options);
|
|
texture2D = GD.Load<Texture2D>(resourcePath);
|
|
break;
|
|
default:
|
|
break;
|
|
}
|
|
}
|
|
|
|
throw new JsonException("Unexpected end when reading Texture2D.");
|
|
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public override void Write(
|
|
Utf8JsonWriter writer,
|
|
Texture2D value,
|
|
JsonSerializerOptions options
|
|
)
|
|
{
|
|
var resolver = options.TypeInfoResolver;
|
|
var resourcePathType = resolver!.GetTypeInfo(typeof(string), options)!;
|
|
|
|
writer.WriteStartObject();
|
|
writer.WritePropertyName("resource_path");
|
|
JsonSerializer.Serialize(writer, value.ResourcePath, resourcePathType);
|
|
writer.WriteEndObject();
|
|
}
|
|
} |