LanguagePackIO.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Text;
  5. using Newtonsoft.Json;
  6. namespace LocalizationTool.Services
  7. {
  8. /// <summary>
  9. /// 语言包数据模型(JSON 格式)。
  10. /// 字段名与主程序 TeamAAS.Localization.LanguageResourcePack 的 JSON 契约完全一致,
  11. /// 两个程序读写同一份 .json 文件。
  12. /// </summary>
  13. public class LanguagePack
  14. {
  15. [JsonProperty("languageCode")]
  16. public string LanguageCode { get; set; }
  17. [JsonProperty("languageName")]
  18. public string LanguageName { get; set; }
  19. [JsonProperty("version")]
  20. public string Version { get; set; } = "1.0.0";
  21. [JsonProperty("author")]
  22. public string Author { get; set; }
  23. /// <summary>翻译字典:中文原文 → 译文。</summary>
  24. [JsonProperty("translations")]
  25. public Dictionary<string, string> Translations { get; set; } = new Dictionary<string, string>();
  26. }
  27. /// <summary>语言包读写(JSON,人类可读)。</summary>
  28. public static class LanguagePackIO
  29. {
  30. /// <summary>
  31. /// 保存为 .json(UTF-8 无 BOM、缩进格式化,方便外部人员直接查看编辑)。
  32. /// </summary>
  33. public static void SaveJson(LanguagePack pack, string filePath)
  34. {
  35. File.WriteAllText(filePath, JsonConvert.SerializeObject(pack, Formatting.Indented),
  36. new UTF8Encoding(false));
  37. }
  38. /// <summary>从 .json 加载。</summary>
  39. public static LanguagePack LoadJson(string filePath)
  40. {
  41. var pack = JsonConvert.DeserializeObject<LanguagePack>(File.ReadAllText(filePath, Encoding.UTF8));
  42. if (pack == null) throw new InvalidDataException("JSON 内容为空");
  43. if (string.IsNullOrWhiteSpace(pack.LanguageCode))
  44. pack.LanguageCode = Path.GetFileNameWithoutExtension(filePath);
  45. if (pack.Translations == null) pack.Translations = new Dictionary<string, string>();
  46. return pack;
  47. }
  48. }
  49. }