C#程序将对象保存为json文件

1、创建文件

// 获取当前程序所在路径,并将要创建的文件命名为info.json 
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
if (!File.Exists(fp))  // 判断是否已有相同文件 
{
    FileStream fs1 = new FileStream(fp, FileMode.Create, FileAccess.ReadWrite);  
    fs1.Close();
}

2、序列化对象转为json并写入文件

string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
File.WriteAllText(fp, JsonConvert.SerializeObject(obj));

3、从文件中反序列化到对象

string fp = System.Windows.Forms.Application.StartupPath + "\\info.json";
Object obji = JsonConvert.DeserializeObject<Object>(File.ReadAllText(fp));  // 尖括号<>中填入对象的类名 
posted @ 2022-01-11 17:01  码农阿亮  阅读(1569)  评论(0)    收藏  举报