Jsonhelper.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using Newtonsoft.Json;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace parkMonitor.entity
  5. {
  6. /// <summary>
  7. /// Json帮助类
  8. /// </summary>
  9. public class JsonHelper
  10. {
  11. /// <summary>
  12. /// 将对象序列化为JSON格式
  13. /// </summary>
  14. /// <param name="o">对象</param>
  15. /// <returns>json字符串</returns>
  16. public static string SerializeObject(object o)
  17. {
  18. string json = JsonConvert.SerializeObject(o);
  19. return json;
  20. }
  21. /// <summary>
  22. /// 解析JSON字符串生成对象实体
  23. /// </summary>
  24. /// <typeparam name="T">对象类型</typeparam>
  25. /// <param name="json">json字符串(eg.{"Adress":"0","Value":"125"})</param>
  26. /// <returns>对象实体</returns>
  27. public static T DeserializeJsonToObject<T>(string json) where T : class
  28. {
  29. JsonSerializer serializer = new JsonSerializer();
  30. StringReader sr = new StringReader(json);
  31. object o = serializer.Deserialize(new JsonTextReader(sr), typeof(T));
  32. T t = o as T;
  33. return t;
  34. }
  35. /// <summary>
  36. /// 解析JSON数组生成对象实体集合
  37. /// </summary>
  38. /// <typeparam name="T">对象类型</typeparam>
  39. /// <param name="json">json数组字符串(eg.[{"Adress":"0","Value":"125"}])</param>
  40. /// <returns>对象实体集合</returns>
  41. public static List<T> DeserializeJsonToList<T>(string json) where T : class
  42. {
  43. JsonSerializer serializer = new JsonSerializer();
  44. StringReader sr = new StringReader(json);
  45. object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
  46. List<T> list = o as List<T>;
  47. return list;
  48. }
  49. /// <summary>
  50. /// 反序列化JSON到给定的匿名对象.
  51. /// </summary>
  52. /// <typeparam name="T">匿名对象类型</typeparam>
  53. /// <param name="json">json字符串</param>
  54. /// <param name="anonymousTypeObject">匿名对象</param>
  55. /// <returns>匿名对象</returns>
  56. public static T DeserializeAnonymousType<T>(string json, T anonymousTypeObject)
  57. {
  58. T t = JsonConvert.DeserializeAnonymousType(json, anonymousTypeObject);
  59. return t;
  60. }
  61. }
  62. }