今天有使用到 先作個 Demo 筆記
下記範例下載
1.) 需要加入參考
System.ServiceModel.Web
System.Runtime.Serialization
2.) 先建立對象
public class Pz
{
public string EMP_ID { get; set; }
public string NAME { get; set; }
public int Age { get; set; }
}
3.) 做序列化
Pz Q = new Pz();
Q.Age = 10;
Q.EMP_ID = "12345";
Q.NAME = "king";
DataContractJsonSerializer ds = new DataContractJsonSerializer(typeof(Pz));
using (MemoryStream ms = new MemoryStream())
{
ds.WriteObject(ms, Q);
output = Encoding.UTF8.GetString(ms.ToArray());
MessageBox.Show("這是序列化:" + output);
}
4.) 反序列化
if (output.Length == 0)
{
return;
}
DataContractJsonSerializer outDs = new DataContractJsonSerializer(typeof(Pz));
using (MemoryStream outMs = new MemoryStream(Encoding.UTF8.GetBytes(output)))
{
Pz QQ = outDs.ReadObject(outMs) as Pz;
MessageBox.Show(QQ.Age + "," + QQ.EMP_ID + "," + QQ.NAME);
}
沒有留言:
張貼留言