在開發過程中,往往會遇到數據類型轉換的情況,根據自己的業務,可能轉換類型有多種,下面就說一下json字符串和字典類型的轉換。
1 public static class JsonUntity 2 { 3 /// <summary> 4 /// 將字典類型序列化為json字符串 5 /// </summary> 6 /// <typeparam name="TKey">字典key</typeparam> 7 /// <typeparam name="TValue">字典value</typeparam> 8 /// <param name="dict">要序列化的字典數據</param> 9 /// <returns>json字符串</returns> 10 public static string SerializeDictionaryToJsonString<TKey, TValue>(Dictionary<TKey, TValue> dict) 11 { 12 if (dict.Count == 0) 13 return ""; 14 15 string jsonStr = JsonConvert.SerializeObject(dict); 16 return jsonStr; 17 } 18 19 /// <summary> 20 /// 將json字符串反序列化為字典類型 21 /// </summary> 22 /// <typeparam name="TKey">字典key</typeparam> 23 /// <typeparam name="TValue">字典value</typeparam> 24 /// <param name="jsonStr">json字符串</param> 25 /// <returns>字典數據</returns> 26 public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr) 27 { 28 if (string.IsNullOrEmpty(jsonStr)) 29 return new Dictionary<TKey, TValue>(); 30 31 Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr); 32 33 return jsonDict; 34 35 } 36 }