using Newtonsoft.Json;
using System;
using System.IO;
using System.Collections.Concurrent;
using System.Reflection;
namespace HKHelper
{
///
/// Json参数服务类
///
public class Json where T : class, new()
{
static string path
{
get
{
Directory.CreateDirectory(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, $"AccessFile\\JSON"));
return $"{AppDomain.CurrentDomain.BaseDirectory}AccessFile\\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)]
*/
}
}