-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathserialization.txt
212 lines (156 loc) · 8.03 KB
/
serialization.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
.. _csharp-serialization:
=============
Serialization
=============
.. facet::
:name: genre
:values: reference
.. meta::
:keywords: class, map, poco, polymorphism, guid, deserialize
:description: Learn to perform serialization with the .NET/C# Driver, including using serializers, custom serializers, and conventions for mapping C# objects to BSON documents.
.. contents:: On this page
:local:
:backlinks: none
:depth: 2
:class: singlecol
.. toctree::
:caption: Serialization
Class Mapping </fundamentals/serialization/class-mapping>
POCOs </fundamentals/serialization/poco>
Polymorphic Objects </fundamentals/serialization/polymorphic-objects>
GUIDs </fundamentals/serialization/guid-serialization>
Overview
--------
In this guide, you can learn how to use the {+driver-long+} to perform
serialization. Serialization is the process of mapping a C# object to a BSON
document for storage in MongoDB.
.. tip:: Serialization
To learn more about serialization, see the :wikipedia:`Serialization <Serialization>`
article on Wikipedia.
Serializers
-----------
Serializers are classes that handle the translation of C# objects to and
from BSON documents. Serializers implement the ``IBsonSerializer``
interface. The {+driver-short+} has many built-in serializers made to handle
primitive types, collection types, and custom classes.
For a full list of available serializers, see the
`Serializers namespace API documentation <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Serializers.html>`__.
Serializer Registry
-------------------
The serializer registry contains all registered serializers that are available
to your application. Many of the built-in serializers are automatically
registered to the serializer registry during startup of your application.
However, before you can use a custom serializer, you must add it to the
serializer registry, as shown in the following example:
.. code-block:: csharp
BsonSerializer.RegisterSerializer(new CustomTypeSerializer());
To access the serializer registry, use the ``SerializerRegistry`` property
of the ``BsonSerializer`` class as follows:
.. code-block:: csharp
var intSerializer = BsonSerializer.SerializerRegistry.GetSerializer<int>();
.. important::
The serializer registry is a global registry. This means that you cannot use
multiple registries in a single application.
Custom Serializers
~~~~~~~~~~~~~~~~~~
To create your own custom serializer, implement the ``IBsonSerializer`` base class, set
the ``ValueType`` member, and override the ``Deserialize()`` and ``Serialize()`` methods.
The following code example shows a custom ``BsonRegularExpression`` serializer:
.. code-block:: csharp
class CustomRegularExpressionSerializer : IBsonSerializer
{
public Type ValueType => typeof(Regex);
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
var type = context.Reader.CurrentBsonType;
switch (type)
{
case BsonType.RegularExpression:
return context.Reader.ReadRegularExpression().AsRegex;
case BsonType.String:
var pattern = context.Reader.ReadString()
return new Regex(pattern);
default:
throw new NotSupportedException($"Cannot convert a {type} to a RegularExpression.");
}
}
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
var regex = (Regex) value;
context.Writer.WriteRegularExpression(regex);
}
}
Opt-in Interfaces
-----------------
The {+driver-short+} has several optional interfaces that your custom serializer
class can implement, depending on the type of data the serializer handles.
IBsonIdProvider
~~~~~~~~~~~~~~~
The `IBsonIdProvider
<{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonIdProvider.html>`__
interface provides the ``GetDocumentId()`` and ``SetDocumentId()``
methods, and is useful if the object you are serializing uses an ``_id`` type other than ``ObjectId``.
IBsonDocumentSerializer
~~~~~~~~~~~~~~~~~~~~~~~
Implementing the `IBsonDocumentSerializer
<{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonDocumentSerializer.html>`__
interface enables the driver to access the member
information of the object you are serializing. This allows the driver to
properly construct type-safe queries when using a custom serializer.
IBsonArraySerializer
~~~~~~~~~~~~~~~~~~~~
Implementing the `IBsonArraySerializer
<{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonArraySerializer.html>`__
interface enables the driver to access serialization information for individual
items in an array.
.. _csharp-conventions:
Conventions
-----------
Convention packs allow you to define and apply
**conventions** to your classes and their members that the driver uses during serialization.
Conventions specify how data is mapped between your
{+language+} objects and MongoDB documents without requiring you to decorate
each class with attributes.
The {+driver-short+} provides built-in conventions that you can use to
customize the serialization process. The following table describes some of the
built-in conventions:
.. list-table::
:header-rows: 1
:widths: 40 60
* - Convention
- Description
* - `CamelCaseElementNameConvention <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.CamelCaseElementNameConvention.html>`__
- Converts element names to camel case during serialization and deserialization.
* - `EnumRepresentationConvention <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.EnumRepresentationConvention.html>`__
- Converts enum values to a specified representation during serialization
and deserialization.
* - `IgnoreExtraElementsConvention <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.IgnoreExtraElementsConvention.html>`__
- Specifies whether to ignore extra elements in a document during deserialization.
* - `ObjectSerializerAllowedTypesConvention <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.ObjectSerializerAllowedTypesConvention.html>`__
- Specifies which types are allowed to be serialized using an object
serializer.
To view a full list of available conventions, see the `Conventions
<{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.html>`__
class reference in the API Documentation.
You can register a convention by instantiating a ``ConventionPack`` with the
specified conventions, then passing it to the
``ConventionRegistry.Register()`` method, as shown in the following example:
.. code-block:: csharp
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
ConventionRegistry.Register("CamelCaseConvention", camelCaseConvention, t => true);
Additional Information
----------------------
To learn more about using the {+driver-short+} to serialize {+language+} objects,
see the following pages:
- :ref:`csharp-class-mapping`
- :ref:`csharp-poco`
- :ref:`csharp-polymorphism`
- :ref:`csharp-guids`
To learn more about any of the methods or types discussed in this
guide, see the following API documentation:
- `SerializerRegistry <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.SerializerRegistry.html>`__
- `BsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.BsonSerializer.html>`__
- `IBsonSerializer <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.IBsonSerializer.html>`__
- `ConventionPack <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.ConventionPack.html>`__
- `ConventionRegistry <{+new-api-root+}/MongoDB.Bson/MongoDB.Bson.Serialization.Conventions.ConventionRegistry.html>`__
- `Register() <{+new-api-root+}/MongoDB.Bson.Serialization.Conventions.ConventionRegistry.Register.html#MongoDB_Bson_Serialization_Conventions_ConventionRegistry_Register_System_String_MongoDB_Bson_Serialization_Conventions_IConventionPack_System_Func_System_Type_System_Boolean__>`__