Nuget安装Newtonsoft后,引入命名空间:
using Newtonsoft.Json;
/// <summary>
/// 读取Josn文件为Model对象
/// </summary>
/// <typeparam name="T">Model对象类型</typeparam>
/// <param name="jspath">Josn文件路径(含【文件名】与【扩展名】)</param>
/// <param name="dm">Model对象</param>
/// <returns>true:读取成功;false:读取失败</returns>
public static bool ReadJson<T>(string jspath, out T dm)
{
if (File.Exists(jspath))
{
string jstr = File.ReadAllText(jspath);
dm = JsonConvert.DeserializeObject<T>(jstr);
return true;
}
else
{
dm = default;
return false;
}
}
/// <summary>
/// 将Model对象写出为Josn文件
/// </summary>
/// <typeparam name="T">Model对象类型</typeparam>
/// <param name="dm">Model对象</param>
/// <param name="jspath">Josn文件路径(含【文件名】与【扩展名】)</param>
/// <returns>true:写出成功;false:写出失败</returns>
public static bool WriteJson<T>(T dm, string jspath)
{
if (Directory.Exists(Path.GetDirectoryName(jspath)))
{
string jstr = JsonConvert.SerializeObject(dm);
File.WriteAllText(jspath, jstr);
return true;
}
else return false;
}