转载自 http://www.cnblogs.com/jams742003/category/225387.html
Json序列化和反序列化指的是:对象序列化为JSON,并可用于从 JSON 反序列化对象
在.net 3.5中
名字空间:System.Runtime.Serialization.Json
但程序集是: System.ServiceModel.Web.dll
(1)DataContractJsonSerializer类
构造方法很多。
参见:http://www.cnblogs.com/ejiyuan/archive/2010/04/09/1708084.html
介绍这个类其中2个方法:
1 WriteObject方法
有好种重载,这里测试一个:
测试:
{
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序列化时,类型不必添加修饰标签
在bindebug里可以看到json串。
有关json串请见:
http://www.cnblogs.com/jams742003/archive/2009/12/29/1634764.html
2 ReadObject方法
重载很多。
测试:
{
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 中)
参见:http://www.cnblogs.com/ejiyuan/archive/2010/04/09/1708084.html
说其中2个方法
1 Serialize方法
Serialize(Object, StringBuilder)
{
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方法
{
string str = File.ReadAllText("jsjson.txt");
JavaScriptSerializer js = new JavaScriptSerializer();
Customer customer = js.Deserialize<Customer>(str);
Console.WriteLine(customer.Name);
}
(3)Json.net
这是一个第三方工具
请见:http://www.cnblogs.com/jams742003/archive/2009/11/04/1595737.html
名字空间:Newtonsoft.Json
添加Newtonsoft.Json.dll程序集
其中2个方法:
1 SerializeObject方法
{
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方法
{
string str = File.ReadAllText("jsonnet.txt");
Customer customer = JsonConvert.DeserializeObject<Customer>(str);
Console.WriteLine(customer.Name);
}