C# MongoDB complex class serialization

后端 未结 3 1701
鱼传尺愫
鱼传尺愫 2020-12-30 15:45

I\'m working with C# MongoDB driver and I have this rather complex JSON struct to save:

{
    \"name\" : \"value\",
    \"age\": 1,
    \"isFemale\": true,
          


        
3条回答
  •  生来不讨喜
    2020-12-30 16:15

    A simple way for dealing with this issue and not have to create additional properties, is registering a custom serializer.

    ComplexTypeSerializer.cs

    namespace MyNamespace.MongoDB.Serializers
    {
        public class ComplexTypeSerializer : SerializerBase
        {
            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 JsonConvert.DeserializeObject>(result);
            }
    
            public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
            {
                var jsonDocument = JsonConvert.SerializeObject(value);
                var bsonDocument = BsonSerializer.Deserialize(jsonDocument);
    
                var serializer = BsonSerializer.LookupSerializer(typeof(BsonDocument));
                serializer.Serialize(context, bsonDocument.AsBsonValue);
            }
        }
    }
    
    
    

    And register it as per http://mongodb.github.io/mongo-csharp-driver/2.3/reference/bson/serialization/

    BsonSerializer.RegisterSerializer(typeof(IDictionary), new ComplexTypeSerializer());
    

    or

    BsonSerializer.RegisterSerializer(typeof(IList>), new ComplexTypeSerializer());
    

    The code below was tested with a simple IDictionary, not sure if it would work with IList>, however if it's not supported, you can create another custom serializer to support it.

    提交回复
    热议问题