JsonUtil.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Furion.FriendlyException;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Runtime.Serialization.Json;
  7. using System.Text;
  8. namespace YBEE.EQM.Core
  9. {
  10. /// <summary>
  11. /// Json工具类
  12. /// </summary>
  13. public static class JsonUtil
  14. {
  15. /// <summary>
  16. /// Object转Josn
  17. /// </summary>
  18. /// <param name="obj"></param>
  19. /// <returns></returns>
  20. public static string ToJson(this object obj)
  21. {
  22. if (obj == null)
  23. {
  24. return null;
  25. }
  26. return JsonConvert.SerializeObject(obj);
  27. }
  28. /// <summary>
  29. /// Json转Object
  30. /// </summary>
  31. /// <typeparam name="T"></typeparam>
  32. /// <param name="str"></param>
  33. /// <returns></returns>
  34. public static T FromJson<T>(this string str)
  35. {
  36. try
  37. {
  38. return JsonConvert.DeserializeObject<T>(str);
  39. }
  40. catch (Exception ex)
  41. {
  42. throw Oops.Oh(ex.Message);
  43. // return default(T);
  44. }
  45. }
  46. /// <summary>
  47. /// 获取Json的Model
  48. /// </summary>
  49. /// <typeparam name="T"></typeparam>
  50. /// <param name="szJson"></param>
  51. /// <returns></returns>
  52. public static T ParseFromJson<T>(string szJson)
  53. {
  54. if (typeof(T) == typeof(IEnumerable<>))
  55. {
  56. }
  57. T obj = Activator.CreateInstance<T>();
  58. using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson)))
  59. {
  60. DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
  61. return (T)serializer.ReadObject(ms);
  62. }
  63. }
  64. /// <summary>
  65. /// string字典
  66. /// </summary>
  67. /// <typeparam name="TKey"></typeparam>
  68. /// <typeparam name="TValue"></typeparam>
  69. /// <param name="jsonStr"></param>
  70. /// <returns></returns>
  71. public static Dictionary<TKey, TValue> DeserializeStringToDictionary<TKey, TValue>(string jsonStr)
  72. {
  73. if (string.IsNullOrEmpty(jsonStr))
  74. return new Dictionary<TKey, TValue>();
  75. Dictionary<TKey, TValue> jsonDict = JsonConvert.DeserializeObject<Dictionary<TKey, TValue>>(jsonStr);
  76. return jsonDict;
  77. }
  78. }
  79. }