[C#][JSON.net] 透過Json.net 取得所有未知物件的Properties.

2013-01-03

 

透過 Json.net 取得所有未知物件的 Properties

因為最近在弄一些東西,會用到比較多 JSON 奇怪的操作,其中有一個需求,就是對未知物件

取得他所有的 Property(Key)..

舉個例子:

{"Name":"DonmaHsu","Age":29,"Memo":"許功蓋~!@#$%^&*()\"'","Friend":{"Name":"Donma Friend","Age":12,"Memo":"當麻朋友","Friend":null}}


這樣的範例,我要取出 Name, Age , Memo , Friend ,並非只有值..


其實透過 JSON.net 很簡單..


C#  Code:


//Source:
//{"Name":"DonmaHsu","Age":29,"Memo":"許功蓋~!@#$%^&*()\"'","Friend":{"Name":"Donma Friend","Age":12,"Memo":"當麻朋友","Friend":null}}
// 透過讀檔方式將 JSON 字串讀入
 var strJson=File.ReadAllText(System.AppDomain.CurrentDomain.BaseDirectory + "data.json");
 
// 因為不確定後面的物件型態,所以都先放 object 去承接
 Dictionary<string, object> values = JsonConvert.DeserializeObject<Dictionary<string, object>>(strJson);
foreach (var value in values)
{
    Response.Write(value.Key+"<br />");
}


這樣印出結果:


Name
Age
Memo
Friend



讀取已知 Property 名稱的資料


如果您原本就已經知道物件名稱,您也可以直接去讀取…


Source :

{"Name":"DonmaHsu","Age":29,"Memo":"許功蓋~!@#$%^&*()\"'","Friend":{"Name":"Donma Friend","Age":12,"Memo":"當麻朋友","Friend":null}}

C#  Code:




JObject jobject = JObject.Parse(strJson);
 
Response.Write(jobject["Friend"]["Name"]);


輸出結果 Donma Friend


因為很常忘記所以筆記一下…
如果,前輩們有更有效率或是更好的方法也歡迎指教 :)


當麻許的超技八 2014 | Donma Hsu Design.