Search code examples
c#.netmongodbbson

.NET MongoDB: Deserialize BsonDocument from BsonType Array


I look for the answer but nothing helps, so I post the question again, hope someone could help me out. Let's say I have a simple JSON string like this:

 [
      {
          "id": 1,
          "name": "A"
      },
      {
          "id": 2,
          "name": "B"
      }
 ]

And here is my code to parse that JSON into BsonDocument

        using (var jsonreader = new JsonReader(json_data))
        {
            var context = BsonDeserializationContext.CreateRoot(jsonreader);
            //Bson Array, how to deserialize???
            var document = collection.DocumentSerializer.Deserialize(context);
            collection.InsertOne(document);
        }

It will return the error "System.FormatException: 'Cannot deserialize a 'BsonDocument' from BsonType 'Array'.'


Solution

  • If you want to directly convert Json to BsonDocument you should do it as following:

    BsonDocument document = BsonDocument.Parse(json_data.toString());
    

    You might want to share more of your code to give clearer picture of what are you trying to do. Anyway, I hope this sorts your issue.