在開發過程中,有時候需要將json字符串轉為字典類型,反之亦然,通常采用.Net的開源類庫Newtonsoft.Json進行序列化,這里我也是采用這個,不過我更喜歡寫擴展方法方便在項目的調用。
首先新建一個擴展類JsonExtensions(類名自己按照自己喜好定義):
public static class JsonExtensions { /// <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; } }
接下來就調用這兩個擴展方法,看看是否可行,這里我寫的是一個單元測試,方便用於測試,寫的一般,大家可以自行回去測試:
[TestClass]
public class DictionaryTest { [TestMethod] public void Can_Serialize_Deserialize() { Dictionary<string, string> paramDictionary = new Dictionary<string, string>(); paramDictionary.Add("one", "productName"); paramDictionary.Add("two", "productColor"); paramDictionary.Add("three", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); paramDictionary.Add("four", DateTime.Now.AddDays(5).ToString("yyyy-MM-dd HH:mm:ss")); string jsonStr = JsonExtensions.SerializeDictionaryToJsonString<string, string>(paramDictionary); var jsonDict = JsonExtensions.DeserializeStringToDictionary<string, string>(jsonStr); List<string> dict1 = new List<string>(); foreach (var item in paramDictionary) { dict1.Add(paramDictionary[item.Key]); } List<string> dict2 = new List<string>(); foreach (var item in jsonDict) { dict2.Add(jsonDict[item.Key]); } int intersect = dict1.Intersect(dict2).Count(); // 交集 int except = dict1.Except(dict2).Count(); // 差集 int union = dict1.Union(dict2).Count(); // 並集 Assert.AreEqual(4, intersect); Assert.AreEqual(0, except); Assert.AreEqual(4, union); Assert.AreEqual("productName", dict2[0]); Assert.AreEqual("productColor", dict2[1]); Assert.AreEqual(4, dict2.Count); } }
輸出結果:

-- 魚頭魚尾
QQ:875755898
