diff --git a/Api/Utility/JsonTool.cs b/Api/Utility/JsonTool.cs new file mode 100644 index 0000000..2ca833c --- /dev/null +++ b/Api/Utility/JsonTool.cs @@ -0,0 +1,85 @@ +using System.Collections; +using System.Text.Json; +using System.Text.Json.Serialization; +using Milimoe.FunGame.Core.Library.Common.Architecture; +using Milimoe.FunGame.Core.Library.Common.JsonConverter; +using Milimoe.FunGame.Core.Service; + +namespace Milimoe.FunGame.Core.Api.Utility +{ + /// + /// 创建一个Json工具类 + /// 此工具类拥有单独的序列化选项,支持添加自定义转换器 + /// 继承自 + /// + public class JsonTool + { + /// + /// 序列化选项 + /// 已经默认添加了下列转换器: + /// , , + /// + public JsonSerializerOptions JsonSerializerOptions => options; + + /// + /// 注册一个自定义转换器,支持 + /// + /// + public void AddConverter(JsonConverter converter) + { + if (!JsonSerializerOptions.Converters.Contains(converter)) + JsonSerializerOptions.Converters.Add(converter); + } + + /// + /// 获取Json字符串 + /// + /// + /// + /// + public string GetString(T obj) => JsonManager.GetString(obj, options); + + /// + /// 反序列化Json对象 + /// + /// + /// + /// + public T? GetObject(string json) => JsonManager.GetObject(json, options); + + /// + /// 反序列化Json对象,此方法可能无法返回正确的类型,请注意辨别 + /// + /// + /// + public object? GetObject(string json) => JsonManager.GetObject(json, options); + + /// + /// 反序列化Hashtable中Key对应的Json对象 + /// + /// + /// + /// + /// + public T? GetObject(Hashtable table, string key) => JsonManager.GetObject(table, key, options); + + /// + /// 反序列化多个Json对象 + /// 注意必须是相同的Json对象才可以使用此方法解析 + /// + /// + /// + /// + public List GetObjects(string json) => JsonManager.GetObjects(json, options); + + /// + /// Private JsonSerializerOptions + /// + private readonly JsonSerializerOptions options = new() + { + WriteIndented = true, + ReferenceHandler = ReferenceHandler.IgnoreCycles, + Converters = { new DateTimeConverter(), new DataTableConverter(), new DataSetConverter() } + }; + } +} diff --git a/Service/JsonManager.cs b/Service/JsonManager.cs index 712621b..12fb50f 100644 --- a/Service/JsonManager.cs +++ b/Service/JsonManager.cs @@ -17,15 +17,6 @@ namespace Milimoe.FunGame.Core.Service ReferenceHandler = ReferenceHandler.IgnoreCycles, Converters = { new DateTimeConverter(), new DataTableConverter(), new DataSetConverter(), new UserConverter(), new RoomConverter() } }; - - /// - /// 注册一个自定义转换器 - /// - /// - internal static void AddConverter(JsonConverter converter) - { - GeneralOptions.Converters.Add(converter); - } /// /// 获取Json字符串