简体   繁体   中英

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.

You can directly use BsonArraySerializer

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

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);

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM