DictionaryUtil.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. using System.Collections.Generic;
  2. using Newtonsoft.Json.Linq;
  3. namespace Alipay.EasySDK.Kernel.Util
  4. {
  5. /// <summary>
  6. /// 字典工具类
  7. /// </summary>
  8. public static class DictionaryUtil
  9. {
  10. /// <summary>
  11. /// 将字典各层次Value中的JObject和JArray转换成C#标准库中的Dictionary和List
  12. /// </summary>
  13. /// <param name="dicObj">输入字典</param>
  14. /// <returns>转换后的输出字典</returns>
  15. public static Dictionary<string, object> ObjToDictionary(Dictionary<string, object> dicObj)
  16. {
  17. Dictionary<string, object> dic = new Dictionary<string, object>();
  18. foreach (string key in dicObj.Keys)
  19. {
  20. if (dicObj[key] is JArray)
  21. {
  22. List<Dictionary<string, object>> dicObjList = ((JArray)dicObj[key]).ToObject<List<Dictionary<string, object>>>();
  23. List<Dictionary<string, object>> dicList = new List<Dictionary<string, object>>();
  24. foreach (Dictionary<string, object> objItem in dicObjList)
  25. {
  26. dicList.Add(ObjToDictionary(objItem));
  27. }
  28. dic.Add(key, dicList);
  29. }
  30. else if (dicObj[key] is JObject)
  31. {
  32. Dictionary<string, object> dicJObj = ((JObject)dicObj[key]).ToObject<Dictionary<string, object>>();
  33. dic.Add(key, ObjToDictionary(dicJObj));
  34. }
  35. else
  36. {
  37. dic.Add(key, dicObj[key]);
  38. }
  39. }
  40. return dic;
  41. }
  42. }
  43. }