Json.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using Newtonsoft.Json;
  2. using Newtonsoft.Json.Converters;
  3. using Newtonsoft.Json.Linq;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Data;
  7. using System.Text;
  8. using System.Text.RegularExpressions;
  9. namespace CZFW.Core.Json
  10. {
  11. public static class Json
  12. {
  13. public static object ToJson(this string json)
  14. {
  15. return json == null ? null : JsonConvert.DeserializeObject(json);
  16. }
  17. public static string ToJson(this object obj)
  18. {
  19. var timeConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
  20. return JsonConvert.SerializeObject(obj, timeConverter);
  21. }
  22. public static string ToJson(this object obj, string datetimeformats)
  23. {
  24. var timeConverter = new IsoDateTimeConverter { DateTimeFormat = datetimeformats };
  25. return JsonConvert.SerializeObject(obj, timeConverter);
  26. }
  27. public static T ToObject<T>(this string json)
  28. {
  29. return json == null ? default(T) : JsonConvert.DeserializeObject<T>(json);
  30. }
  31. public static List<T> ToList<T>(this string json)
  32. {
  33. return json == null ? null : JsonConvert.DeserializeObject<List<T>>(json);
  34. }
  35. public static DataTable ToTable(this string json)
  36. {
  37. return json == null ? null : JsonConvert.DeserializeObject<DataTable>(json);
  38. }
  39. public static JObject ToJObject(this string json)
  40. {
  41. return json == null ? JObject.Parse("{}") : JObject.Parse(json.Replace("&nbsp;", ""));
  42. }
  43. public static T Deserialize<T>(string jsonString)
  44. {
  45. return JsonConvert.DeserializeObject<T>(jsonString);
  46. //return new JavaScriptSerializer
  47. //{
  48. // MaxJsonLength = int.MaxValue
  49. //}.Deserialize<T>(jsonString);
  50. }
  51. public static string Serialize(object obj)
  52. {
  53. return ToJson(obj);
  54. //return Regex.Replace(new JavaScriptSerializer
  55. //{
  56. // MaxJsonLength = int.MaxValue
  57. //}.Serialize(obj), @"\\/Date\((\d+)\)\\/", match =>
  58. //{
  59. // DateTime dt = new DateTime(1970, 1, 1);
  60. // dt = dt.AddMilliseconds(long.Parse(match.Groups[1].Value));
  61. // dt = dt.ToLocalTime();
  62. // return dt.ToString("yyyy-MM-dd HH:mm:ss");
  63. //});
  64. }
  65. }
  66. }