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.
 
 

86 lines
2.7 KiB

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