1. 程式人生 > >.NET 生成JSON 檔案

.NET 生成JSON 檔案

//構成配置檔案路徑
string con_file_path = @"" + serverAppPath + pId + @".json";
if (File.Exists(con_file_path))
{
File.Delete(con_file_path);

}
FileStream fs = File.Create(con_file_path);
fs.Close();
fs.Dispose();
//把模型資料寫到檔案
FileStream _file = new FileStream(con_file_path, FileMode.Create, FileAccess.ReadWrite);
using (StreamWriter sw = new StreamWriter(_file))
{
try
{
JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;

//構建Json.net的寫入流
JsonWriter writer = new JsonTextWriter(sw);
//把模型資料序列化並寫入Json.net的JsonWriter流中
serializer.Serialize(writer, model);
writer.Close();
sw.Close();
}
catch (Exception ex)
{
ex.Message.ToString();
}

}