I have a document with a property of type “object” referring subdocs of different schemas. We are using BsonSerializer to deserialize it, but this class is throwing a BsonInternalException error for subdocs with properties of type decimal: Invalid Bson Type
It looks like decimal deserialization is not supported for decimal types. When should we expect to be supported?
DB Sample
{
…
Current: { amount: NumberDecimal(“1”) }
…
}
CSharp Sample
BsonSerializer.Deserialize(bsonDoc.Current.AsBsonDocument.ToString())
Hi, @Daniel_Comanici,
Welcome to the MongoDB Community Forums. I understand that you’re encountering BsonInternalException
when trying to deserialize a JSON string containing a decimal. I have reproduced the issue and filed CSHARP-4496.
This bug is due to JsonReader
missing support for BsonType.Decimal128
. However you don’t need to render the BsonDocument
to JSON (which is what ToString()
is doing) and then reparse it. You can simply access the BsonDocument
.
var bsonDoc = new BsonDocument { { "amount", new Decimal128(42.42m)} };
Console.WriteLine(bsonDoc["amount"]);
The return value of the bsonDoc["amount"]
is a BsonValue
. If you need a specific type, you can call bsonDoc["amount"].AsDecimal
. You can also inspect bsonDoc["amount"].BsonType
if you need to switch on different types. There are also IsDecimal
and other methods to determine if the BsonValue
is a particular type.
Hopefully this helps solve your immediate problem. Please follow CSHARP-4496 for the fix to JsonReader
.
Sincerely,
James