using System; using AibisDream.Utility; using Newtonsoft.Json; using UnityEngine; namespace AibisDream.SaveSystem { /// /// 与 JSON 互转;写入时带上 。 /// 被 调用,业务层通常不直接使用。 /// public static class SnapshotSerializer { private static readonly JsonSerializerSettings Settings = new() { TypeNameHandling = TypeNameHandling.None, ReferenceLoopHandling = ReferenceLoopHandling.Ignore, NullValueHandling = NullValueHandling.Ignore }; public static string Serialize(SaveSnapshot snapshot) { snapshot.schemaVersion = SaveSnapshotSchema.CurrentVersion; return JsonConvert.SerializeObject(snapshot, Formatting.Indented, Settings); } public static SaveSnapshot Deserialize(string json) { var snapshot = JsonConvert.DeserializeObject(json, Settings); if (snapshot.schemaVersion != SaveSnapshotSchema.CurrentVersion) { Debug.LogWarning( $"[SnapshotSerializer] schemaVersion {snapshot.schemaVersion} != {SaveSnapshotSchema.CurrentVersion},按当前结构读取。"); } return snapshot; } public static void SaveToFile(SaveSnapshot snapshot, string pathWithoutExtension) { var json = Serialize(snapshot); var dir = System.IO.Path.GetDirectoryName(JsonUtil.FormatAsJsonPath(pathWithoutExtension)); if (!string.IsNullOrEmpty(dir)) { System.IO.Directory.CreateDirectory(dir); } System.IO.File.WriteAllText(JsonUtil.FormatAsJsonPath(pathWithoutExtension), json); } public static SaveSnapshot LoadFromFile(string pathWithoutExtension) { var json = System.IO.File.ReadAllText(JsonUtil.FormatAsJsonPath(pathWithoutExtension)); return Deserialize(json); } } }