轉自曾是土木人原文 C#:Json數據反序列化為Dictionary並根據關鍵字獲取指定的值
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" } ] } } }
問題:如何獲取header中的數據行,以便顯示在界面上?
效果圖:

將json數據轉成dictionary的代碼:
/// <summary>
/// 將json數據反序列化為Dictionary
/// </summary>
/// <param name="jsonData">json數據</param>
/// <returns></returns>
private Dictionary<string, object> JsonToDictionary(string jsonData)
{
//實例化JavaScriptSerializer類的新實例
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
//將指定的 JSON 字符串轉換為 Dictionary<string, object> 類型的對象
return jss.Deserialize<Dictionary<string, object>>(jsonData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
使用方法:
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;
}
}
}
