C#中JSON字串和Dictionary字典型別的相互轉換

風靈使發表於2018-07-07

在開發過程中,往往會遇到資料型別轉換的情況,根據自己的業務,可能轉換型別有多種,下面就說一下json字串和字典型別的轉換。

public static class JsonUntity
    {
        /// <summary>
        /// 將字典型別序列化為json字串
        /// </summary>
        /// <typeparam name="TKey">字典key</typeparam>
        /// <typeparam name="TValue">字典value</typeparam>
        /// <param name="dict">要序列化的字典資料</param>
        /// <returns>json字串</returns>
        public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict)
        {
            if (dict.Count == 0)
                return "";

            string jsonStr = JsonConvert.SerializeObject(dict);
            return jsonStr;
        }

        /// <summary>
        /// 將json字串反序列化為字典型別
        /// </summary>
        /// <typeparam name="TKey">字典key</typeparam>
        /// <typeparam name="TValue">字典value</typeparam>
        /// <param name="jsonStr">json字串</param>
        /// <returns>字典資料</returns>
        public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
        {
            if (string.IsNullOrEmpty(jsonStr))
                return new Dictionary<TKey, TValue>();

            Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);

            return jsonDict;

        }
    }

List集合序列化可使用:

        /// <summary>
        /// JSON序列化
        /// </summary>
        public string JsonSerializer<T>(T t)
        {
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream();
            ser.WriteObject(ms, t);
            string jsonString = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            return jsonString;
        }

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;
        }
    }
}

相關文章