MongoHelper.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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(byte[] bytes, Type type)
  27. {
  28. return BsonSerializer.Deserialize(bytes, type);
  29. }
  30. public static T FromBson<T>(byte[] bytes, int index = 0)
  31. {
  32. using (MemoryStream memoryStream = new MemoryStream(bytes))
  33. {
  34. memoryStream.Seek(index, SeekOrigin.Begin);
  35. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  36. }
  37. }
  38. public static T FromBson<T>(byte[] bytes, int index, int count)
  39. {
  40. using (MemoryStream memoryStream = new MemoryStream(bytes))
  41. {
  42. memoryStream.Seek(index, SeekOrigin.Begin);
  43. memoryStream.Seek(index + count, SeekOrigin.End);
  44. return (T)BsonSerializer.Deserialize(memoryStream, typeof(T));
  45. }
  46. }
  47. }
  48. }