using System;
using System.Collections.Generic;
using UnityEngine;
namespace BaseGames.Localization
{
///
/// 本地化表 JSON 的对称解析 / 序列化(唯一格式真相源)。
///
/// 表格式:{ "entries": [ { "key": "...", "value": "..." } ] }
///
/// 运行时加载()与编辑器写盘(LocalizationFileIO)
/// 都经此类,确保读写格式永远一致,杜绝"格式漂移"。
///
public static class LocalizationSerializer
{
///
/// 将表 JSON 文本解析为 key→value 字典。
/// 返回 null 表示格式无效(entries 缺失)。空 key 条目被跳过。
///
public static Dictionary Parse(string jsonText)
{
if (string.IsNullOrEmpty(jsonText)) return null;
StringTableJson parsed;
try { parsed = JsonUtility.FromJson(jsonText); }
catch { return null; }
if (parsed?.entries == null) return null;
var dict = new Dictionary(parsed.entries.Count, StringComparer.Ordinal);
foreach (var entry in parsed.entries)
if (!string.IsNullOrEmpty(entry.key))
dict[entry.key] = entry.value ?? string.Empty;
return dict;
}
///
/// 将 key→value 字典序列化为表 JSON 文本({entries:[…]} 格式,pretty print)。
/// 该输出可被 与运行时加载器无损还原。
///
/// 要序列化的字典。
/// 是否按 key 的序数顺序排序(默认 true,减少版本控制 diff 噪声)。
public static string Serialize(IReadOnlyDictionary dict, bool sortKeys = true)
{
var table = new StringTableJson { entries = new List(dict?.Count ?? 0) };
if (dict != null)
{
IEnumerable keys = dict.Keys;
if (sortKeys)
{
var sorted = new List(dict.Keys);
sorted.Sort(StringComparer.Ordinal);
keys = sorted;
}
foreach (var key in keys)
table.entries.Add(new StringEntry { key = key, value = dict[key] ?? string.Empty });
}
// JsonUtility 正确转义引号/反斜杠/换行,且保留中日韩字符原文(不转 \uXXXX)。
return JsonUtility.ToJson(table, prettyPrint: true);
}
// ── 序列化辅助类型(运行时与编辑器共用)────────────────────────────────
[Serializable]
internal class StringTableJson
{
public List entries;
}
[Serializable]
internal class StringEntry
{
public string key;
public string value;
}
}
}