在开发过程中,有时候需要将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