转载自
Json序列化和反序列化指的是:对象序列化为JSON,并可用于从 JSON 反序列化对象
在.net 3.5中
名字空间:System.Runtime.Serialization.Json
但程序集是: System.ServiceModel.Web.dll
(1)DataContractJsonSerializer类
构造方法很多。
参见:
介绍这个类其中2个方法:
1 WriteObject方法
有好种重载,这里测试一个:
public override void WriteObject(Stream stream,Object graph)
测试:
public void TestJsonSerialize() { Customer customer = new Customer { Unid = 1, Name = "宋江", Call = "89589689" }; DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Customer)); FileStream fs = new FileStream("json.txt", FileMode.Create); ds.WriteObject(fs, customer); fs.Close(); }
进行Json序列化时,类型不必添加修饰标签
在bin\debug里可以看到json串。
有关json串请见:
2 ReadObject方法
重载很多。
public override Object ReadObject(Stream stream)
测试:
public void TestJsonDeserialize() { DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Customer)); FileStream fs = new FileStream("json.txt", FileMode.Open); var cc = ds.ReadObject(fs); fs.Close(); }
(2)JavaScriptSerializer类
为启用 AFAX 的应用程序提供序列化和反序列化功能
名字空间:System.Web.Script.Serialization
程序集:System.Web.Extensions(在 System.Web.Extensions.dll 中)
参见:
说其中2个方法
1 Serialize方法
Serialize(Object) Serialize(Object, StringBuilder)
public void TestJsSerialize() { Customer customer = new Customer { Unid = 1, Name = "宋江", Call = "89589689" }; JavaScriptSerializer js = new JavaScriptSerializer(); Console.WriteLine(js.Serialize(customer)); }
输出串:{"Unid":1,"Name":"宋江","Call":"89589689"}
2 Deserialize方法
public void TestJsDeserialize() { string str = File.ReadAllText("jsjson.txt"); JavaScriptSerializer js = new JavaScriptSerializer(); Customer customer = js.Deserialize<Customer>(str); Console.WriteLine(customer.Name); }
(3)Json.net
这是一个第三方工具
请见:
名字空间:Newtonsoft.Json
添加Newtonsoft.Json.dll程序集
其中2个方法:
1 SerializeObject方法
public void TestJsonnetSerialize() { Customer customer = new Customer { Unid = 1, Name = "宋江", Call = "89589689" }; string strJson=JsonConvert.SerializeObject(customer); StreamWriter sw = File.CreateText("jsonnet.txt"); sw.Write(strJson); sw.Close(); }
2 DeserializeObject方法
public void TestJsonnetDeserialize() { string str = File.ReadAllText("jsonnet.txt"); Customer customer = JsonConvert.DeserializeObject<Customer>(str); Console.WriteLine(customer.Name); }