[.net]JSON String to Object

[.net]JSON String to Object

記錄使用DataContractJsonSerializer,把JSON String轉成Object。

假設JSON String如下,

{"property":"EmpId","direction":"ASC"}

那我們就建一個SortInfo的Class來接,


public class SortInfo
{
    public string property { get; set; }
    public string direction { get; set; }
}

 

 

然後透過DataContractJsonSerializer轉成SortInfo Class。


using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;


private void button1_Click(object sender, EventArgs e)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SortInfo));
    MemoryStream msmdl = new MemoryStream(Encoding.Unicode.GetBytes("{"property":"EmpId","direction":"ASC"}" ));
    SortInfo sortParam = (SortInfo)serializer.ReadObject(msmdl);
}

 

 

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^