1. 程式人生 > >C#:Json資料反序列化為Dictionary並根據關鍵字獲取指定的值

C#:Json資料反序列化為Dictionary並根據關鍵字獲取指定的值

private void button1_Click(object sender, EventArgs e){//Json資料string json = "{\"dataSet\":{\"header\":{\"returnCode\":\"0\",\"errorInfo\":\"HTTP請求錯誤\",\"version\":\"V1.0R010\",\"totalRows\":\"2000\",\"returnRows\":\"20\"},\"fieldDefine\":{\"assetId\":\"string\",\"serverIdcId\":\"int\",\"inputTime\":\"datetime\"},\"data\":{\"row\":[{\"AssetId\":\"TCNS2006888\",\"ServerIdcId\":\"1\",\"InputTime\":\"2008-12-12\"},{\"AssetId\":\"TCNS2006889\",\"ServerIdcId\":\"2\",\"InputTime\":\"2008-1-1\"}]}}}
"; Dictionary<string, object> dic = JsonToDictionary(json);//將Json資料轉成dictionary格式 Dictionary<string, object> dataSet=(Dictionary<string, object>)dic["dataSet"];//使用KeyValuePair遍歷資料foreach (KeyValuePair<string, object> item in dataSet) {if (item.Key.ToString() == "header
")//獲取header資料 {var subItem=(Dictionary<string,object>)item.Value;foreach (var str in subItem) { textBox1.AppendText(str.Key + ":" + str.Value+"\r\n");//顯示到介面 }break; } }}