使用DataContractJsonSerializer进行JSON序列化的JSONHelper类

前端之家收集整理的这篇文章主要介绍了使用DataContractJsonSerializer进行JSON序列化的JSONHelper类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
  1. public static class JSONHelper
  2. {
  3. /// <summary>
  4. /// 将对象转化为Json字符串
  5. /// </summary>
  6. /// <typeparam name="T">对象类型</typeparam>
  7. /// <param name="instanse">对象本身</param>
  8. /// <returns>JSON字符串</returns>
  9. public static string Serializer<T>(this T instanse)
  10. {
  11. try
  12. {
  13. DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
  14. using (MemoryStream ms = new MemoryStream())
  15. {
  16. js.WriteObject(ms,instanse);
  17. ms.Flush();
  18. ms.Seek(0,SeekOrigin.Begin);
  19. StreamReader sr = new StreamReader(ms);
  20. return sr.ReadToEnd();
  21. }
  22. }
  23. catch
  24. {
  25. return String.Empty;
  26. }
  27. }
  28. /// <summary>
  29. /// 将字符串转化为JSON对象,如果转换失败,返回default(T)
  30. /// </summary>
  31. /// <typeparam name="T">对象类型</typeparam>
  32. /// <param name="s">字符串</param>
  33. /// <returns>转换值</returns>
  34. public static T Deserializer<T>(this string s)
  35. {
  36. try
  37. {
  38. DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(T));
  39. using (MemoryStream ms = new MemoryStream())
  40. {
  41. StreamWriter sw = new StreamWriter(ms);
  42. sw.Write(s);
  43. sw.Flush();
  44. ms.Seek(0,SeekOrigin.Begin);
  45. return (T)js.ReadObject(ms);
  46. }
  47. }
  48. catch
  49. {
  50. return default(T);
  51. }
  52. }
  53. }

猜你在找的Json相关文章