MongoHelper.cs 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System;
  2. using System.IO;
  3. using MongoDB.Bson;
  4. using MongoDB.Bson.IO;
  5. using MongoDB.Bson.Serialization;
  6. namespace Base
  7. {
  8. public static class MongoHelper
  9. {
  10. public static string ToJson(object obj)
  11. {
  12. return obj.ToJson();
  13. }
  14. public static string ToJson(object obj, JsonWriterSettings settings)
  15. {
  16. return obj.ToJson(settings);
  17. }
  18. public static T FromJson<T>(string str)
  19. {
  20. return BsonSerializer.Deserialize<T>(str);
  21. }
  22. public static object FromJson(Type type, string str)
  23. {
  24. return BsonSerializer.Deserialize(str, type);
  25. }
  26. public static byte[] ToBson(object obj)
  27. {
  28. return obj.ToBson();
  29. }
  30. public static object FromBson(Type type, byte[] bytes)
  31. {
  32. return BsonSerializer.Deserialize(bytes, type);
  33. }
  34. public static object FromBson(Type type, byte[] bytes, int index, int count)
  35. {
  36. using (MemoryStream memoryStream = new MemoryStream(bytes, index, count))
  37. {
  38. return BsonSerializer.Deserialize(memoryStream, type);
  39. }
  40. }
  41. public static T FromBson<T>(byte[] bytes)
  42. {
  43. using (MemoryStream memoryStream = new MemoryStream(bytes))
  44. {
  45. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  46. }
  47. }
  48. public static T FromBson<T>(byte[] bytes, int index, int count)
  49. {
  50. return (T) FromBson(typeof (T), bytes, index, count);
  51. }
  52. public static T Clone<T>(T t)
  53. {
  54. return FromBson<T>(ToBson(t));
  55. }
  56. }
  57. }