(1)首先定义一个类Customer作为示例。
public class Customer
{
public int Unid { get; set; }
public string CustomerName { get; set; }
}
(2)添加引用System.ServiceModel 和 System.ServiceModel.Web。
添加
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO.MemoryMappedFiles;
(3)定义函数实现JSon的序列化和反序列化。
public string ToJson<T>(T t)
{
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream();
ds.WriteObject(ms, t);
string strReturn = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
return strReturn;
}
public T FromJson<T>(string strJson) where T:class
{
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(T));
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(strJson));
return ds.ReadObject(ms) as T;
}
(4)编写函数实现对上述函数调用,实现具体的实体对象序列化和反序列化操作。
private void button1_Click(object sender, EventArgs e)
{
Customer cc = new Customer { Unid = 1, CustomerName = "Tom" };
string strJsons = ToJson<Customer>(cc);
textBox1.Text = textBox1.Text + (strJsons);//在文本框中输出。
string strJson = "{\"CustomerName\":\"Tom\",\"Unid\":1}";
Customer c = FromJson<Customer>(strJson);
textBox1.Text = textBox1.Text + (c.Unid + " " + c.CustomerName);//在文本框中输出。
}