using Newtonsoft.Json;
using System;
using System.IO;
using System.Collections.Concurrent;
using System.Reflection;
namespace BPASmartClient.Helper
{
///
/// Json参数服务类
///
public class Json 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();
///
/// 保存数据
///
public static void Save()
{
string outjson = JsonConvert.SerializeObject(Data);
File.WriteAllText(path, outjson);
}
///
/// 获取保存的数据
///
public static void Read()
{
if (File.Exists(path))
{
string JsonString = File.ReadAllText(path);
var result = JsonConvert.DeserializeObject(JsonString);
if (result != null) { Data = result; }
}
}
///
/// 保存带接口的对象
///
public static void SaveInterface()
{
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;
string outjson = JsonConvert.SerializeObject(Data, Formatting.Indented, settings);
File.WriteAllText(path, outjson);
}
///
/// 获取带接口对象的字符串
///
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(JsonString, settings);
if (result != null) { Data = result; }
}
}
/*
使用反序列化接口对象的方法
一、使用 SaveInterface 方法保存成字符串,使用 ReadInterface 方法获取对象
二、在接口属性上加一个特性 [JsonProperty(TypeNameHandling = TypeNameHandling.Auto)]
*/
}
}