简体   繁体   中英

.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'.'

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.

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