DynamicJsonHelper.cs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using Newtonsoft.Json.Linq;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Xml.Linq;
  8. namespace KdanCommon.Helpers
  9. {
  10. public static class DynamicJsonHelper
  11. {
  12. public static dynamic ToDynamicJson(string jsonString)
  13. {
  14. try
  15. {
  16. JObject jo = JObject.Parse(jsonString);
  17. return jo as dynamic;
  18. }
  19. catch
  20. {
  21. return null;
  22. }
  23. }
  24. public static T GetValueSafety<T>(dynamic value, T defaultValue)
  25. {
  26. try
  27. {
  28. var val = (T)value;
  29. if (val == null)
  30. return defaultValue;
  31. else
  32. return (T)value;
  33. }
  34. catch
  35. {
  36. return defaultValue;
  37. }
  38. }
  39. public static List<dynamic> GetArraySafety(dynamic value)
  40. {
  41. try
  42. {
  43. if (value is JArray)
  44. return ((JArray)value).Cast<dynamic>().ToList();
  45. }
  46. catch { }
  47. return null;
  48. }
  49. }
  50. }