Reputation: 37
I have a C# object with about 500 properties, some of them complex types. The Json documents are imported via XML and it works 100%. I can also query the collection and successfully serialize the Json document into the C# object. The problem is that when I make a change to the object and use collection.Save(object); it creates Json properties for ALL of the C# properties even though they are NULL, so now my document looks like this:
{
"_id" : "AA00001",
"Product" : {
"Reference" : "AA00001",
"Type" : "02",
"Code" : null,
"Property 1" : null,
"Property 2" : null,
"Property 3" : null,
.
.
.
}
The original document looked like this before the C# save
{
"_id" : "AA00001",
"Product" : {
"Reference" : "AA00001",
"Type" : "02"
.
.
.
Is there a way to tell the driver not to save the empty/null values?
Thank you.
Upvotes: 2
Views: 1458
Reputation: 46311
You can do this by registering a ConventionPack:
var pack = new ConventionPack();
pack.Add(new IgnoreIfNullConvention(true));
ConventionRegistry.Register("ignore nulls",
pack,
t => true);
IgnoreIfNull
will prevent the fields from being serialized. There's also a IgnoreIfDefaultConvention
which also works for value types.
For more Details on how to register these, you might want to refer to another question here on SO.
Upvotes: 1