using System; using Newtonsoft.Json; namespace AlicizaX.Runtime { public static partial class Utility { /// /// JSON 相关的实用函数。 /// public static partial class Json { /// /// 将对象序列化为 JSON 字符串。 /// /// 要序列化的对象。 /// 序列化后的 JSON 字符串。 public static string ToJson(object obj) { try { return JsonConvert.SerializeObject(obj); } catch (Exception exception) { if (exception is GameFrameworkException) { throw; } throw new GameFrameworkException(Text.Format("Can not convert to JSON with exception '{0}'.", exception), exception); } } /// /// 将 JSON 字符串反序列化为对象。 /// /// 对象类型。 /// 要反序列化的 JSON 字符串。 /// 反序列化后的对象。 public static T ToObject(string json) { try { return JsonConvert.DeserializeObject(json); } catch (Exception exception) { if (exception is GameFrameworkException) { throw; } throw new GameFrameworkException(Text.Format("Can not convert to object with exception '{0}'.", exception), exception); } } /// /// 将 JSON 字符串反序列化为对象。 /// /// 对象类型。 /// 要反序列化的 JSON 字符串。 /// 反序列化后的对象。 public static object ToObject(Type objectType, string json) { if (objectType == null) { throw new GameFrameworkException("Object type is invalid."); } try { return JsonConvert.DeserializeObject(json, objectType); } catch (Exception exception) { if (exception is GameFrameworkException) { throw; } throw new GameFrameworkException(Text.Format("Can not convert to object with exception '{0}'.", exception), exception); } } } } }