JSON字符串和Dictionary字典类型的相互转换

在开发过程中,往往会遇到数据类型转换的情况,根据自己的业务,可能转换类型有多种,下面就说一下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     }

 

posted @ 2016-11-24 10:21  zhangzhenpeng  阅读(36354)  评论(0编辑  收藏  举报