using GFramework.Core.Abstractions.Serializer; using Newtonsoft.Json; namespace GFramework.Game.Serializer; /// /// JSON序列化器实现类,用于将对象序列化为JSON字符串或将JSON字符串反序列化为对象 /// public sealed class JsonSerializer : IRuntimeTypeSerializer { /// /// 将指定类型的对象序列化为JSON字符串 /// /// 要序列化的对象类型 /// 要序列化的对象实例 /// 序列化后的JSON字符串 public string Serialize(T value) { return JsonConvert.SerializeObject(value); } /// /// 将JSON字符串反序列化为指定类型的对象 /// /// 要反序列化的目标类型 /// 要反序列化的JSON字符串数据 /// 反序列化后的对象实例 /// 当无法反序列化数据时抛出 public T Deserialize(string data) { return JsonConvert.DeserializeObject(data) ?? throw new ArgumentException("Cannot deserialize data"); } /// /// 将对象序列化为JSON字符串(使用运行时类型) /// /// 要序列化的对象实例 /// 对象的运行时类型 /// 序列化后的JSON字符串 public string Serialize(object obj, Type type) { return JsonConvert.SerializeObject(obj, type, null); } /// /// 将JSON字符串反序列化为指定类型的对象(使用运行时类型) /// /// 要反序列化的JSON字符串数据 /// 反序列化目标类型 /// 反序列化后的对象实例 /// 当无法反序列化到指定类型时抛出 public object Deserialize(string data, Type type) { return JsonConvert.DeserializeObject(data, type) ?? throw new ArgumentException($"Cannot deserialize to {type.Name}"); } }