using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.IO;
using System.Text;
namespace MainForm.Common
{
public class JsonFileHelper
{
///
/// 读取JSON文件
///
/// 返回的类型
/// 打开的文件路径
/// 实体类
public static T ReadjsonT(string fileName)
{
//using (System.IO.StreamReader file = System.IO.File.OpenText(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName))
using (System.IO.StreamReader file = System.IO.File.OpenText(fileName))
{
return JsonConvert.DeserializeObject(file.ReadToEnd());
}
}
//Config config = new Config();
//config= JsonfileTools.ReadjsonT("SendDataZCCAconfig.json");
///
/// 写入JSON文件
///
///
/// 保存使用的文件路径
/// 实体类
/// 成功状态
public static bool WritejsonT(string fileName, T tParameter)
{
//string fp = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + fileName;
string fp = fileName;
try
{
File.WriteAllText(fp, JsonConvert.SerializeObject(tParameter)); // 覆盖写入
return true;
}
catch
{
return false;
}
}
///
/// 修改-Value通过Key(AppSetting)
///
/// 文件路径
/// 需要修改的key
/// 更改为的值
///
public static void ModifyValueByKey(string filePath, string[] key, string value)
{
try
{
if (!File.Exists(filePath))
{
throw new Exception("需要修改的json文件不存在!");
}
string jsonStr = File.ReadAllText(filePath, Encoding.UTF8); // 读取文件流
JObject json = JObject.Parse(jsonStr); // 解析成json
//json[key] = value; // 修改需要修改的字段
switch (key.Length)
{
case 1:
json[key[0]] = value;
break;
case 2:
json[key[0]][key[1]] = value;
break;
case 3:
json[key[0]][key[1]][key[2]] = value;
break;
default:
// 目前只用到最多三层的
break;
}
jsonStr = Convert.ToString(json);
File.WriteAllText(filePath, jsonStr, Encoding.UTF8);
}
catch
{
throw new Exception($"修改{filePath}文件出错!");
}
}
}
}