终端一体化运控平台
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

96 line
3.0 KiB

  1. using Newtonsoft.Json;
  2. using System;
  3. using System.IO;
  4. using System.Collections.Concurrent;
  5. using System.Reflection;
  6. namespace BPASmartClient.Helper
  7. {
  8. /// <summary>
  9. /// Json参数服务类
  10. /// </summary>
  11. public class Json<T> where T : class, new()
  12. {
  13. //private static string DeviceType = ActionManage.GetInstance.SendResult("GetDeviceType").ToString();
  14. //static string path
  15. //{
  16. // get
  17. // {
  18. // Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\{DeviceType}\\JSON"));
  19. // return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\{DeviceType}\\JSON\\{typeof(T).Name}.json";
  20. // }
  21. //}
  22. static string path
  23. {
  24. get
  25. {
  26. Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"{LocaPath.GetInstance.FilePath}\\JSON"));
  27. return $"{AppDomain.CurrentDomain.BaseDirectory}{LocaPath.GetInstance.FilePath}JSON\\{typeof(T).Name}.json";
  28. }
  29. }
  30. public static T Data { get; set; } = new T();
  31. /// <summary>
  32. /// 保存数据
  33. /// </summary>
  34. public static void Save()
  35. {
  36. string outjson = JsonConvert.SerializeObject(Data);
  37. File.WriteAllText(path, outjson);
  38. }
  39. /// <summary>
  40. /// 获取保存的数据
  41. /// </summary>
  42. public static void Read()
  43. {
  44. if (File.Exists(path))
  45. {
  46. string JsonString = File.ReadAllText(path);
  47. var result = JsonConvert.DeserializeObject<T>(JsonString);
  48. if (result != null) { Data = result; }
  49. }
  50. }
  51. /// <summary>
  52. /// 保存带接口的对象
  53. /// </summary>
  54. public static void SaveInterface()
  55. {
  56. var settings = new JsonSerializerSettings();
  57. settings.TypeNameHandling = TypeNameHandling.Objects;
  58. string outjson = JsonConvert.SerializeObject(Data, Formatting.Indented, settings);
  59. File.WriteAllText(path, outjson);
  60. }
  61. /// <summary>
  62. /// 获取带接口对象的字符串
  63. /// </summary>
  64. public static void ReadInterface()
  65. {
  66. if (File.Exists(path))
  67. {
  68. var settings = new JsonSerializerSettings();
  69. settings.TypeNameHandling = TypeNameHandling.Objects;
  70. string JsonString = File.ReadAllText(path);
  71. var result = JsonConvert.DeserializeObject<T>(JsonString, settings);
  72. if (result != null) { Data = result; }
  73. }
  74. }
  75. /*
  76. 使用反序列化接口对象的方法
  77. 一、使用 SaveInterface 方法保存成字符串,使用 ReadInterface 方法获取对象
  78. 二、在接口属性上加一个特性 [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
  79. */
  80. }
  81. }