终端一体化运控平台
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 

82 行
2.5 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. static string path
  14. {
  15. get
  16. {
  17. Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\JSON"));
  18. return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\JSON\\{typeof(T).Name}.json";
  19. }
  20. }
  21. public static T Data { get; set; } = new T();
  22. /// <summary>
  23. /// 保存数据
  24. /// </summary>
  25. public static void Save()
  26. {
  27. string outjson = JsonConvert.SerializeObject(Data);
  28. File.WriteAllText(path, outjson);
  29. }
  30. /// <summary>
  31. /// 获取保存的数据
  32. /// </summary>
  33. public static void Read()
  34. {
  35. if (File.Exists(path))
  36. {
  37. string JsonString = File.ReadAllText(path);
  38. var result = JsonConvert.DeserializeObject<T>(JsonString);
  39. if (result != null) { Data = result; }
  40. }
  41. }
  42. /// <summary>
  43. /// 保存带接口的对象
  44. /// </summary>
  45. public static void SaveInterface()
  46. {
  47. var settings = new JsonSerializerSettings();
  48. settings.TypeNameHandling = TypeNameHandling.Objects;
  49. string outjson = JsonConvert.SerializeObject(Data, Formatting.Indented, settings);
  50. File.WriteAllText(path, outjson);
  51. }
  52. /// <summary>
  53. /// 获取带接口对象的字符串
  54. /// </summary>
  55. public static void ReadInterface()
  56. {
  57. if (File.Exists(path))
  58. {
  59. var settings = new JsonSerializerSettings();
  60. settings.TypeNameHandling = TypeNameHandling.Objects;
  61. string JsonString = File.ReadAllText(path);
  62. var result = JsonConvert.DeserializeObject<T>(JsonString, settings);
  63. if (result != null) { Data = result; }
  64. }
  65. }
  66. /*
  67. 使用反序列化接口对象的方法
  68. 一、使用 SaveInterface 方法保存成字符串,使用 ReadInterface 方法获取对象
  69. 二、在接口属性上加一个特性 [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
  70. */
  71. }
  72. }