The following test snippet demonstrates an InvalidCastException occurring in SerializeObject when an object value is null or even BsonNull.Value. If the value is changed to 42, serialization works fine.
var bson = new BsonDocument
{
{ "key", null /*BsonNull.Value*/ }
};
// the following fails with an inexplicable InvalidCastException...
var json = Newtonsoft.Json.JsonConvert.SerializeObject(
bson,
new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Include
});
Console.WriteLine(json);
"using MongoDB.Bson" and "using Newtonsoft.Json" are in effect. Json version is v12.0.1.
Please note that I have also considered using the BsonDocument ToJson method but it exhibits other problems (dealing with enum values), so I am no longer considering this as a work-around.