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();
}
}

posted on 2018-06-13 16:27  hbgjh  阅读(7361)  评论(0编辑  收藏  举报