坚持记录实属不易,希望友善多金的码友能够随手点一个赞。
共同创建氛围更加良好的开发者社区!
谢谢~
命名空间
using Newtonsoft.Json;
读取Json
核心代码
//核心代码
using (StreamReader file = File.OpenText(filePath))
{
JsonSerializer serializer = new JsonSerializer();
var ret = (类型)serializer.Deserialize(file, typeof(类型));
}
示例
Dictionary<string, double> LoadDictionaryFromFile()
{
Dictionary<string, double> ret = new Dictionary<string, double>();
try
{
if (!Directory.Exists(folderPath))
{
//检查文件目录是否存在
Directory.CreateDirectory(folderPath);
}
var filePath = Path.Combine(folderPath, FileName);
if (!File.Exists(filePath))
{
File.Create(filePath);
}
else
{
//核心代码
using (StreamReader file = File.OpenText(filePath))
{
JsonSerializer serializer = new JsonSerializer();
ret = (Dictionary<string, double>)serializer.Deserialize(file, typeof(Dictionary<string, double>));
}
}
}
catch (Exception ex)
{
MainDeviceProvider.Instance.Logger.Error("解析出现错误!",ex);
}
return ret;
}
写入Json
核心代码
var filePath = Path.Combine(folderPath, FileName);
string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);
File.WriteAllText(filePath, data);
示例
void SaveDataToFile()
{
try
{
var filePath = Path.Combine(folderPath, FileName);
string data = JsonConvert.SerializeObject(dataDictionary, Formatting.Indented);
File.WriteAllText(filePath, data);
}
catch(Exception ex)
{
MainDeviceProvider.Instance.Logger.Error("写入出现错误!", ex);
}
}