using GFramework.Core.Abstractions.Serializer; using Newtonsoft.Json; using NewtonsoftJsonException = Newtonsoft.Json.JsonException; namespace GFramework.Game.Serializer; /// /// JSON序列化器实现类,用于将对象序列化为JSON字符串或将JSON字符串反序列化为对象 /// public sealed class JsonSerializer : IRuntimeTypeSerializer { private readonly JsonSerializerSettings _settings; /// /// 初始化 JSON 序列化器。 /// /// 可选的 Newtonsoft.Json 配置;不提供时使用默认配置。 public JsonSerializer(JsonSerializerSettings? settings = null) { _settings = settings ?? new JsonSerializerSettings(); } /// /// 获取当前序列化器使用的 Newtonsoft.Json 配置实例。 /// public JsonSerializerSettings Settings => _settings; /// /// 获取当前序列化器使用的自定义转换器集合。 /// public IList Converters => _settings.Converters; /// /// 将指定类型的对象序列化为JSON字符串 /// /// 要序列化的对象类型 /// 要序列化的对象实例 /// 序列化后的JSON字符串 public string Serialize(T value) { return JsonConvert.SerializeObject(value, _settings); } /// /// 将对象序列化为JSON字符串(使用运行时类型) /// /// 要序列化的对象实例 /// 对象的运行时类型 /// 序列化后的JSON字符串 public string Serialize(object obj, Type type) { ArgumentNullException.ThrowIfNull(obj); ArgumentNullException.ThrowIfNull(type); return JsonConvert.SerializeObject(obj, type, _settings); } /// /// 将JSON字符串反序列化为指定类型的对象 /// /// 要反序列化的目标类型 /// 要反序列化的JSON字符串数据 /// 反序列化后的对象实例 /// 当无法反序列化数据时抛出 public T Deserialize(string data) { return (T)DeserializeCore( data, typeof(T), static (json, type, settings) => JsonConvert.DeserializeObject(json, settings)); } /// /// 将JSON字符串反序列化为指定类型的对象(使用运行时类型) /// /// 要反序列化的JSON字符串数据 /// 反序列化目标类型 /// 反序列化后的对象实例 /// 当无法反序列化到指定类型时抛出 public object Deserialize(string data, Type type) { return DeserializeCore( data, type, static (json, targetType, settings) => JsonConvert.DeserializeObject(json, targetType, settings)); } private object DeserializeCore( string data, Type targetType, Func deserialize) { ArgumentException.ThrowIfNullOrWhiteSpace(data); ArgumentNullException.ThrowIfNull(targetType); ArgumentNullException.ThrowIfNull(deserialize); try { var result = deserialize(data, targetType, _settings); if (result == null) { throw new InvalidOperationException( $"Deserialization returned null for target type '{targetType.FullName}'."); } return result; } catch (Exception ex) when (ex is NewtonsoftJsonException or InvalidCastException or ArgumentException) { throw new InvalidOperationException( $"Failed to deserialize JSON to target type '{targetType.FullName}'.", ex); } } }