LitJsonManager.cs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. using System.IO;
  2. using UnityEngine;
  3. using LitJson;
  4. using System.Text;
  5. namespace SC.XR.Unity.Module_PlatformAccount
  6. {
  7. public class LitJsonManager : LitJsonMgr
  8. {
  9. public override void Init<T>(string key, T t)
  10. {
  11. PlayerPrefs.DeleteKey(key);
  12. t = new T();
  13. PlayerPrefs.SetString(key,JsonMapper.ToJson(t));
  14. WriteJson<T>(key, t);
  15. }
  16. public override T ReadJson<T>(string key, ref T t)
  17. {
  18. if (!File.Exists(DirectoryPath))
  19. {
  20. Directory.CreateDirectory(DirectoryPath);
  21. }
  22. string filePath = DirectoryPath + key + ".txt";
  23. if (PlayerPrefs.GetString(key) == "")
  24. {
  25. Init(key, t);
  26. }
  27. if (!File.Exists(filePath))
  28. {
  29. Init(key, t);
  30. }
  31. StreamReader sr = new StreamReader(filePath);
  32. JsonReader jr = new JsonReader(sr);
  33. t = JsonMapper.ToObject<T>(jr);
  34. sr.Close();
  35. return t;
  36. }
  37. public override void WriteJson<T>(string key, T t)
  38. {
  39. base.WriteJson<T>(key, t);
  40. string json = "";
  41. json = JsonMapper.ToJson(t);
  42. string filePath = DirectoryPath + key + ".txt";
  43. if (!File.Exists(DirectoryPath))
  44. {
  45. Directory.CreateDirectory(DirectoryPath);
  46. }
  47. if (!File.Exists(filePath))
  48. {
  49. FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate);
  50. StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8);
  51. sw.Write(json);
  52. sw.Close();
  53. fileStream.Close();
  54. }
  55. else
  56. {
  57. StreamWriter sw = new StreamWriter(filePath);
  58. sw.Write(json);
  59. sw.Close();
  60. }
  61. }
  62. public override void Save()
  63. {
  64. base.Save();
  65. }
  66. }
  67. }