title: Custom BsonSerializer for generic value types
body: <p>I have written a custom Bson serializer attribute.</p>
  <p>It works fine when the value passed to the Serialize method is of ValueKind &quot;Object&quot;.</p>
  <p>But if the ValueKind is of any other datatype like string, int, bool, etc it gives error as &quot;Cannot deserialize a BsonDocument from BsonType String&quot;</p>
  <p>How to make it generic to work for all data types and decorate with an attribute.</p>
  <p>Model:</p>
  <pre><code>[BsonSerializer(typeof(CustomSerialize))]
  [BsonElement(&quot;response&quot;)]
  public object response { get; set; }   
  </code></pre>
  <p>CustomSerialize class:</p>
  <pre><code>   public class CustomSerialize : SerializerBase&lt;Object&gt;
      {
          public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
          {
              var element = (JsonElement)value;
              BsonDocument document = BsonDocument.Parse(element.GetRawText());
              var serializer = BsonSerializer.LookupSerializer(typeof(BsonDocument));
              serializer.Serialize(context, document.AsBsonValue);
          }
  
          public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
          {
              var serializer = BsonSerializer.LookupSerializer(typeof(BsonDocument));
              var document = serializer.Deserialize(context, args);
              var bsonDocument = document.ToBsonDocument();
              var result = BsonExtensionMethods.ToJson(bsonDocument);
              return JsonSerializer.Deserialize&lt;object&gt;(result);
          }
      }
  </code></pre>