ReFuel.Gltf/ReFuel.Gltf/GltfSerializedExtensionProvider.cs
2025-10-12 14:33:16 +03:00

46 lines
1.3 KiB
C#
Executable File

using System;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace ReFuel.Gltf
{
public class GltfSerializedExtensionProvider<T> : IGltfExtensionProvider<T>
{
public string Name { get; }
public Type? DataType { get; } = typeof(T);
public GltfSerializedExtensionProvider(string name)
{
Name = name;
if (typeof(T).GetCustomAttribute<JsonSerializableAttribute>() is null)
throw new Exception("This type is not JSON serializable.");
}
public T ParseExtension(JsonElement element)
{
return JsonSerializer.Deserialize<T>(element) ?? throw new Exception("Could not deserialize extension object.");
}
public object ParseExtensionObject(JsonElement element)
{
return ParseExtension(element)!;
}
public void WriteExtension(T value, Utf8JsonWriter writer)
{
JsonSerializer.Serialize(writer, value);
}
public void WriteExtensionObject(object obj, Utf8JsonWriter writer)
{
if (obj is T extensionType)
{
WriteExtension(extensionType, writer);
}
else throw new Exception($"Unexpected type of object {obj.GetType()}.");
}
}
}