首先,從NuGet上下載JSON .Net,安裝到所需項目中。
對象obj保存到文件的步驟:
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));
從文件中讀取對象obj的步驟:
直接從文件中反序列化到對象即可
string fp = System.Windows.Forms.Application.StartupPath + "\\info.json"; Object obji = JsonConvert.DeserializeObject<Object>(File.ReadAllText(fp)); // 尖括號<>中填入對象的類名
更多JSON .Net的相關操作可以參考其官網。