MongoHelper.cs 1.5 KB

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