JsonHelperForPC.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*******************************************************************************
  2. * Copyright(c) 2014 DongkeSoft All rights reserved. / Confidential
  3. * 类的信息:
  4. * 1.程序名称:JsonHelperForPC.cs
  5. * 2.功能描述:Json转换处理,PC端使用。
  6. * 编辑履历:
  7. * 作者 日期 版本 修改内容
  8. * 付斌 2018/08/08 1.00 新建
  9. *******************************************************************************/
  10. using System;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Converters;
  13. namespace Dongke.IBOSS.PRD.Basics.Library
  14. {
  15. public static class JsonHelperForPC
  16. {
  17. private static JsonSerializerSettings _jsonSettings;
  18. static JsonHelperForPC()
  19. {
  20. IsoDateTimeConverter datetimeConverter = new IsoDateTimeConverter();
  21. datetimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss";
  22. _jsonSettings = new JsonSerializerSettings();
  23. _jsonSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
  24. //_jsonSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
  25. _jsonSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
  26. _jsonSettings.Converters.Add(datetimeConverter);
  27. }
  28. /// <summary>
  29. /// 将指定的对象序列化成 JSON 数据。
  30. /// </summary>
  31. /// <param name="obj">要序列化的对象。</param>
  32. /// <returns></returns>
  33. public static string ToJson(object obj)
  34. {
  35. try
  36. {
  37. if (null == obj)
  38. return null;
  39. return JsonConvert.SerializeObject(obj, Formatting.None, _jsonSettings);
  40. }
  41. catch (Exception ex)
  42. {
  43. throw ex;
  44. }
  45. }
  46. /// <summary>
  47. /// 将指定的 JSON 数据反序列化成指定对象。
  48. /// </summary>
  49. /// <typeparam name="T">对象类型。</typeparam>
  50. /// <param name="json">JSON 数据。</param>
  51. /// <returns></returns>
  52. public static T FromJson<T>(string json)
  53. {
  54. try
  55. {
  56. return JsonConvert.DeserializeObject<T>(json, _jsonSettings);
  57. }
  58. catch (Exception ex)
  59. {
  60. throw ex;
  61. }
  62. }
  63. }
  64. }