C# NEWTONSOFT.JSON寫json文件


//寫JSON文件config.json內容如下:

{"Name":"lotname","Address":"wenzhou","Devices":{"id":"001111","name":"相機","ip":"192.168.1.1"},"Doors":"4"}

C#源碼如下:

public static void Writejson()
{
//子集
Hashtable device = new Hashtable();
device.Add("id", "001111");
device.Add("name", "相機");
device.Add("ip", "192.168.1.1");


LotModel lot = new LotModel(); //實體模型類
lot.Name = "lotname";
lot.Address = "wenzhou";
lot.Devices = device; //注意是子集
lot.Doors = "4";

//序列化
string js1 = JsonConvert.SerializeObject(lot);
string js2 = JsonConvert.SerializeObject(device);

//反序列化
LotModel debc1 = JsonConvert.DeserializeObject<LotModel>(js1);
LotModel debc2 = JsonConvert.DeserializeObject<LotModel>(js2);

//找到服務器物理路徑
//string serverAppPath = Request.PhysicalApplicationPath.ToString();
string serverAppPath = @"d:\";
//構成配置文件路徑
string con_file_path = @"" + serverAppPath + @"config.json";


if (!File.Exists(con_file_path))
{
File.Create(con_file_path);
}

//把模型數據寫到文件
using (StreamWriter sw = new StreamWriter(con_file_path))
{
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, lot);
//ser.Serialize(writer, ht);
writer.Close();
sw.Close();
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM