3

I want to retrieve the list of Booking collection.

Some of the collection have,

Case 1

 "Countries": [{
                "Destinations": [{
                    "Code": "CHX",
                    "Name": "French Alps"
                }],
                "Code": {
                    "_t": "JsonElement"
                },
                "Name": {
                    "_t": "JsonElement"
                }
            }]

and some of them have,

Case 2

 "Countries": [{
                "Destinations": [{
                    "Code": "DXB",
                    "Name": "Dubai"
                }],
                "Code": "AE",
                "Name": "United Arab Emirates"
            }]

Note that code and name fields.

and the model for retrieve list is

    {
        public List<DestinationDocument> Destinations { get; set; } = new List<DestinationDocument>();

        public string Code { get; set; }

        public string Name { get; set; }
    }

I want to to ignore the code and name when they are not string (i.e I want to ignore code and name of case 1 . but not Destinations of case 1 ).

How can I do that using mongoDb driver.

I tried SetIgnoreExtraElements. but it does not work.

1 Answer 1

0

Easiest way to control the way MongoDB .NET deserializes your data is probably to create your own serializer and return null whenever it encounters anything different than BsonType.String. It can be done in two steps. Define your custom deserialization logic:

public class IgnoreDocumentSerializer : SerializerBase<string>
{
    public override string Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
    {
        var serializer = BsonSerializer.LookupSerializer(typeof(string));
        if(context.Reader.CurrentBsonType == BsonType.String)
        {
            return (string)serializer.Deserialize(context, args);
        }

        if (context.Reader.CurrentBsonType == BsonType.Document)
        {
            context.Reader.ReadRawBsonDocument();
        }

        return null;
    }
}

and decorate your model properties with BsonSerializer attribute:

public class Country
{
    public List<DestinationDocument> Destinations { get; set; } = new List<DestinationDocument>();

    [BsonSerializer(typeof(IgnoreDocumentSerializer))]
    public string Code { get; set; }

    [BsonSerializer(typeof(IgnoreDocumentSerializer))]
    public string Name { get; set; }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.