Files
aibis-dream/Assets/Scripts/SaveSystem/SnapshotSerializer.cs
T

116 lines
2.2 KiB
C#

using System;
using AibisDream.Utility;
using Newtonsoft.Json;
using UnityEngine;
namespace AibisDream.SaveSystem
{
/// <summary>
/// <see cref="SaveSnapshot"/> 与 JSON 互转;写入时带上 <see cref="SaveSnapshotSchema.CurrentVersion"/>。
/// 被 <see cref="SnapshotPersistence"/> 调用,业务层通常不直接使用。
/// </summary>
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<SaveSnapshot>(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);
}
}
}