Chadit
Chadit

Reputation: 965

C# Mongo BsonSerializer.Deserialize Ignore elements that do not exist

Is there a flat that will tell the C# Mongo BsonSerializer to ignore elements that do not exist in the poco class

Example collection

Animal {"Type" : "Cat", "Skill" : "Jump"}
Animal {"Type" : "Dog", "Skill" : "Bark", "Owner" : "Jimmy"}

If the cat C# class only has

public string Type {get;set;}
public string Skill {get;set;}

When I attempt to execute the following

 var test = BsonSerializer.Deserialize<Animal>(result);

The first item will work fine, the second one will throw an exception that Owner does not exist.

Upvotes: 3

Views: 6805

Answers (3)

Victor Trusov
Victor Trusov

Reputation: 1222

Or you can use Convention to do it for all types at once

var conventionPack = new ConventionPack { new IgnoreExtraElementsConvention(true) };
ConventionRegistry.Register("IgnoreExtraElements", conventionPack, _ => true);

Upvotes: 3

FireAlkazar
FireAlkazar

Reputation: 1880

Use [BsonIgnoreExtraElements] attribute on Cat class.
From attribute summary:

Specifies whether extra elements should be ignored when this class is deserialized.

Upvotes: 14

Carey Tzou
Carey Tzou

Reputation: 77

Maybe you can deserialize as an object, and use dynamic to receive it.

dynamic test = BsonSerializer.Deserialize<object>(result);

Upvotes: 0

Related Questions