MongoHelper.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. using System.IO;
  3. using MongoDB.Bson;
  4. using MongoDB.Bson.IO;
  5. using MongoDB.Bson.Serialization;
  6. namespace Common.Helper
  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 byte[] ToBson(object obj)
  23. {
  24. return obj.ToBson();
  25. }
  26. public static object FromBson(Type type, byte[] bytes)
  27. {
  28. return BsonSerializer.Deserialize(bytes, type);
  29. }
  30. public static object FromBson(Type type, byte[] bytes, int index, int count)
  31. {
  32. using (MemoryStream memoryStream = new MemoryStream(bytes))
  33. {
  34. memoryStream.Seek(index, SeekOrigin.Begin);
  35. memoryStream.Seek(index + count, SeekOrigin.End);
  36. return BsonSerializer.Deserialize(memoryStream, type);
  37. }
  38. }
  39. public static T FromBson<T>(byte[] bytes, int index = 0)
  40. {
  41. using (MemoryStream memoryStream = new MemoryStream(bytes))
  42. {
  43. memoryStream.Seek(index, SeekOrigin.Begin);
  44. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  45. }
  46. }
  47. public static T FromBson<T>(byte[] bytes, int index, int count)
  48. {
  49. using (MemoryStream memoryStream = new MemoryStream(bytes))
  50. {
  51. memoryStream.Seek(index, SeekOrigin.Begin);
  52. memoryStream.Seek(index + count, SeekOrigin.End);
  53. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  54. }
  55. }
  56. }
  57. }