MongoHelper.cs 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. using System.Collections.Generic;
  8. namespace ETModel
  9. {
  10. public static class MongoHelper
  11. {
  12. public static void Init()
  13. {
  14. BsonSerializer.RegisterSerializer(new EnumSerializer<NumericType>(BsonType.String));
  15. }
  16. public static string ToJson(object obj)
  17. {
  18. return obj.ToJson();
  19. }
  20. public static string ToJson(object obj, JsonWriterSettings settings)
  21. {
  22. return obj.ToJson(settings);
  23. }
  24. public static T FromJson<T>(string str)
  25. {
  26. return BsonSerializer.Deserialize<T>(str);
  27. }
  28. public static object FromJson(Type type, string str)
  29. {
  30. return BsonSerializer.Deserialize(str, type);
  31. }
  32. public static byte[] ToBson(object obj)
  33. {
  34. return obj.ToBson();
  35. }
  36. public static object FromBson(Type type, byte[] bytes)
  37. {
  38. return BsonSerializer.Deserialize(bytes, type);
  39. }
  40. public static object FromBson(Type type, byte[] bytes, int index, int count)
  41. {
  42. using (MemoryStream memoryStream = new MemoryStream(bytes, index, count))
  43. {
  44. return BsonSerializer.Deserialize(memoryStream, type);
  45. }
  46. }
  47. public static T FromBson<T>(byte[] bytes)
  48. {
  49. using (MemoryStream memoryStream = new MemoryStream(bytes))
  50. {
  51. return (T) BsonSerializer.Deserialize(memoryStream, typeof (T));
  52. }
  53. }
  54. public static T FromBson<T>(byte[] bytes, int index, int count)
  55. {
  56. return (T) FromBson(typeof (T), bytes, index, count);
  57. }
  58. public static T Clone<T>(T t)
  59. {
  60. return FromBson<T>(ToBson(t));
  61. }
  62. public static void AvoidAOT()
  63. {
  64. ArraySerializer<int> aint = new ArraySerializer<int>();
  65. ArraySerializer<string> astring = new ArraySerializer<string>();
  66. ArraySerializer<long> along = new ArraySerializer<long>();
  67. EnumerableInterfaceImplementerSerializer<List<int>> e =
  68. new EnumerableInterfaceImplementerSerializer<List<int>>();
  69. EnumerableInterfaceImplementerSerializer<List<int>, int> elistint =
  70. new EnumerableInterfaceImplementerSerializer<List<int>, int>();
  71. }
  72. }
  73. }