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

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;

        }

    }

}