JsonHelper.cs 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using Newtonsoft.Json;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. namespace HTEXLib.Helpers.ShapeHelpers
  6. {
  7. public static class JsonHelper
  8. {
  9. static JsonSerializerSettings settings = new JsonSerializerSettings()
  10. {
  11. ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
  12. PreserveReferencesHandling = PreserveReferencesHandling.None
  13. };
  14. /// <summary>
  15. /// 使用json序列化为字符串
  16. /// </summary>
  17. /// <param name="dateTimeFormat">默认null,即使用json.net默认的序列化机制,如:"\/Date(1439335800000+0800)\/"</param>
  18. /// <returns></returns>
  19. public static string ToJson(this object input, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss", bool ignoreNullValue = true, bool isIndented = false)
  20. {
  21. settings.NullValueHandling = ignoreNullValue ? Newtonsoft.Json.NullValueHandling.Ignore : NullValueHandling.Include;
  22. if (!string.IsNullOrWhiteSpace(dateTimeFormat))
  23. {
  24. var jsonConverter = new List<JsonConverter>()
  25. {
  26. new Newtonsoft.Json.Converters.IsoDateTimeConverter(){ DateTimeFormat = dateTimeFormat }//如: "yyyy-MM-dd HH:mm:ss"
  27. };
  28. settings.Converters = jsonConverter;
  29. }
  30. //no format
  31. var format = isIndented ? Newtonsoft.Json.Formatting.Indented : Formatting.None;
  32. var json = JsonConvert.SerializeObject(input, format, settings);
  33. return json;
  34. }
  35. /// <summary>
  36. /// 从序列化字符串里反序列化
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="input"></param>
  40. /// <param name="dateTimeFormat">默认null,即使用json.net默认的序列化机制</param>
  41. /// <returns></returns>
  42. public static T FromJson<T>(this string input, string dateTimeFormat = "yyyy-MM-dd HH:mm:ss", bool ignoreNullValue = true)
  43. {
  44. var settings = new JsonSerializerSettings()
  45. {
  46. ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
  47. PreserveReferencesHandling = PreserveReferencesHandling.Objects,
  48. };
  49. settings.NullValueHandling = ignoreNullValue ? Newtonsoft.Json.NullValueHandling.Ignore : NullValueHandling.Include;
  50. if (!string.IsNullOrWhiteSpace(dateTimeFormat))
  51. {
  52. var jsonConverter = new List<JsonConverter>()
  53. {
  54. new Newtonsoft.Json.Converters.IsoDateTimeConverter(){ DateTimeFormat = dateTimeFormat }//如: "yyyy-MM-dd HH:mm:ss"
  55. };
  56. settings.Converters = jsonConverter;
  57. }
  58. return JsonConvert.DeserializeObject<T>(input, settings);
  59. }
  60. }
  61. }