'Cannot deserialize a 'BsonDocument' from BsonType 'Array'

I'm getting this error at trying to parse a json string to BsonDocument.

The C# code is:

        string jsonText = System.IO.File.ReadAllText(@"source.json");
        var document = BsonDocument.Parse(jsonText);
        var collection = _database.GetCollection<BsonDocument>("collectionName");
        collection.InsertOne(document);

While last C# code works fine for a single document:

{
 "field1": 1,
 "field2": "value",
 "field3": "value",
 "field4": "value",
 "arr1": [
   {
    "arrField1": 1,
    "arrField2": "value"
   }
         ]
}

I'm getting the exception Cannot deserialize a 'BsonDocument' from BsonType 'Array' while parsing a json array document:

[
 {
  "field1": 1,
  "field2": "value",
  "field3": "value",
  "field4": "value",
  "arr1": [
    {
      "arrField1": 1,
      "arrField2": "value"
    }
          ]
 },
 {
  "field1": 2,
  "field2": "value",
  "field3": "value",
  "field4": "value",
  "arr1": [
    {
      "arrField1": 1,
      "arrField2": "value"
    }
          ]
  }
]

Any idea on how can I parse a json with multiple elements? Thanks in advance.



Solution 1:[1]

You can directly use BsonArraySerializer

using (var jsonReader = new JsonReader(text))
{
   var serializer = new BsonArraySerializer();
   var bsonArray = serializer.Deserialize(BsonDeserializationContext.CreateRoot(jsonReader));
}

Solution 2:[2]

Further to the answer of @rnofenko You can run over the array and insert document by document

BsonArray bsonArray;

using (var jsonReader = new JsonReader(text))
{
     var serializer = new BsonArraySerializer();
     bsonArray = serializer.Deserialize(BsonDeserializationContext.CreateRoot(jsonReader));
}

var collection = database.GetCollection<BsonDocument>("SomeObject_Collection");

foreach (BsonValue bsonValue in bsonArray)
{
   var b = bsonValue.ToBsonDocument();
   await collection.InsertOneAsync(b);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rnofenko
Solution 2 Dave