关键词搜索

源码搜索 ×
×

C# Json 序列化与反序列化二

发布2015-08-19浏览2540次

详情内容

  1. /// <summary>
  2. /// 将对象转换为 JSON 字符串
  3. /// </summary>
  4. /// <typeparam name="T"></typeparam>
  5. /// <param name="input"></param>
  6. /// <returns></returns>
  7. public static string ScriptSerialize<T>(T input)
  8. {
  9. string _jsonString = string.Empty;
  10. if (input != null)
  11. {
  12. JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
  13. _serializerHelper.MaxJsonLength = int.MaxValue;
  14. _jsonString = _serializerHelper.Serialize(input);
  15. }
  16. return _jsonString;
  17. }
  18. /// <summary>
  19. /// 将指定的 JSON 字符串转换为 T 类型的对象
  20. /// </summary>
  21. /// <typeparam name="T"></typeparam>
  22. /// <param name="input"></param>
  23. /// <returns></returns>
  24. public static T ScriptDeserialize<T>(string input)
  25. {
  26. T rtn = default(T);
  27. if (!string.IsNullOrEmpty(input))
  28. {
  29. JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
  30. rtn = _serializerHelper.Deserialize<T>(input);
  31. }
  32. return rtn;
  33. }
  34. #region 利用JavaScriptSerializer将对象序列化成JSON
  35. /// <summary>
  36. /// 利用JavaScriptSerializer将对象序列化成JSON字符串
  37. /// </summary>
  38. /// <typeparam name="T">泛型</typeparam>
  39. /// <param name="entityList">对象集合</param>
  40. /// <returns>json</returns>
  41. public static string Serialize<T>(IEnumerable<T> entityList) where T : class
  42. {
  43. string _jsonString = string.Empty;
  44. if (entityList != null)
  45. {
  46. JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
  47. _serializerHelper.MaxJsonLength = int.MaxValue;
  48. _jsonString = _serializerHelper.Serialize(entityList);
  49. }
  50. return _jsonString;
  51. }
  52. #endregion
  53. #region 利用JavaScriptSerializer将json字符串反序列化
  54. /// <summary>
  55. ///利用JavaScriptSerializer将json字符串反序列化
  56. /// </summary>
  57. /// <typeparam name="T">泛型</typeparam>
  58. /// <param name="jsonString"></param>
  59. /// <returns>IEnumerable</returns>
  60. public static IEnumerable<T> Deserialize<T>(string jsonString) where T : class
  61. {
  62. IEnumerable<T> _list = null;
  63. if (!string.IsNullOrEmpty(jsonString))
  64. {
  65. JavaScriptSerializer _serializerHelper = new JavaScriptSerializer();
  66. _list = _serializerHelper.Deserialize<IEnumerable<T>>(jsonString);
  67. }
  68. return _list;
  69. }
  70. #endregion


C# Json 序列化与反序列化一

Josn序列化与反序列化demo

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载