Guest User

Untitled

a guest
Dec 9th, 2018
60
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /// <summary>
  2. /// JObject扩展
  3. /// </summary>
  4. public static class JObjectExtensions
  5. {
  6. /// <summary>
  7. /// 将JObject转化成字典
  8. /// </summary>
  9. /// <param name="json"></param>
  10. /// <returns></returns>
  11. public static IDictionary<string, object> ToDictionary(this JToken json)
  12. {
  13. var propertyValuePairs = json.ToObject<Dictionary<string, object>>();
  14. ProcessJObjectProperties(propertyValuePairs);
  15. ProcessJArrayProperties(propertyValuePairs);
  16. return propertyValuePairs;
  17. }
  18.  
  19. private static void ProcessJObjectProperties(IDictionary<string, object> propertyValuePairs)
  20. {
  21. var objectPropertyNames = (from property in propertyValuePairs
  22. let propertyName = property.Key
  23. let value = property.Value
  24. where value is JObject
  25. select propertyName).ToList();
  26.  
  27. objectPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToDictionary((JObject)propertyValuePairs[propertyName]));
  28. }
  29.  
  30. private static void ProcessJArrayProperties(IDictionary<string, object> propertyValuePairs)
  31. {
  32. var arrayPropertyNames = (from property in propertyValuePairs
  33. let propertyName = property.Key
  34. let value = property.Value
  35. where value is JArray
  36. select propertyName).ToList();
  37.  
  38. arrayPropertyNames.ForEach(propertyName => propertyValuePairs[propertyName] = ToArray((JArray)propertyValuePairs[propertyName]));
  39. }
  40.  
  41. /// <summary>
  42. /// 数据项转换到数组
  43. /// </summary>
  44. /// <param name="array"></param>
  45. /// <returns></returns>
  46. public static object[] ToArray(this JArray array)
  47. {
  48. return array.ToObject<object[]>().Select(ProcessArrayEntry).ToArray();
  49. }
  50.  
  51. private static object ProcessArrayEntry(object value)
  52. {
  53. switch (value)
  54. {
  55. case JObject _:
  56. return ToDictionary((JObject)value);
  57. case JArray _:
  58. return ToArray((JArray)value);
  59. default:
  60. return value;
  61. }
  62. }
  63. }
RAW Paste Data