|
- using Newtonsoft.Json;
- using System;
- using System.IO;
- using System.Collections.Concurrent;
- using System.Reflection;
-
- namespace BPASmartClient.Helper
- {
- /// <summary>
- /// Json参数服务类
- /// </summary>
- public class Json<T> where T : class, new()
- {
-
- //private static string DeviceType = ActionManage.GetInstance.SendResult("GetDeviceType").ToString();
-
- //static string path
- //{
- // get
- // {
- // Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\{DeviceType}\\JSON"));
- // return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\{DeviceType}\\JSON\\{typeof(T).Name}.json";
- // }
- //}
-
- static string path
- {
- get
- {
- Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"JSON"));
- return $"{AppDomain.CurrentDomain.BaseDirectory}JSON\\{typeof(T).Name}.json";
- }
- }
-
- public static T Data { get; set; } = new T();
-
- /// <summary>
- /// 保存数据
- /// </summary>
- public static void Save()
- {
- string outjson = JsonConvert.SerializeObject(Data);
- File.WriteAllText(path, outjson);
- }
-
-
-
- /// <summary>
- /// 获取保存的数据
- /// </summary>
- public static void Read()
- {
- if (File.Exists(path))
- {
- string JsonString = File.ReadAllText(path);
- var result = JsonConvert.DeserializeObject<T>(JsonString);
- if (result != null) { Data = result; }
- }
- }
-
- /// <summary>
- /// 保存带接口的对象
- /// </summary>
- public static void SaveInterface()
- {
- var settings = new JsonSerializerSettings();
- settings.TypeNameHandling = TypeNameHandling.Objects;
- string outjson = JsonConvert.SerializeObject(Data, Formatting.Indented, settings);
- File.WriteAllText(path, outjson);
- }
-
- /// <summary>
- /// 获取带接口对象的字符串
- /// </summary>
- public static void ReadInterface()
- {
- if (File.Exists(path))
- {
- var settings = new JsonSerializerSettings();
- settings.TypeNameHandling = TypeNameHandling.Objects;
- string JsonString = File.ReadAllText(path);
- var result = JsonConvert.DeserializeObject<T>(JsonString, settings);
- if (result != null) { Data = result; }
- }
- }
-
- /*
- 使用反序列化接口对象的方法
- 一、使用 SaveInterface 方法保存成字符串,使用 ReadInterface 方法获取对象
- 二、在接口属性上加一个特性 [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
- */
-
-
- }
- }
|