简体   繁体   English

.NET MongoDB:从BsonType数组反序列化BsonDocument

[英].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: 假设我有一个简单的JSON字符串,如下所示:

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

And here is my code to parse that JSON into BsonDocument 这是我的代码,将JSON解析为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'.' 它将返回错误“ System.FormatException:'无法从BsonType'Array'反序列化'BsonDocument'。

If you want to directly convert Json to BsonDocument you should do it as following: 如果要直接将Json转换为BsonDocument,则应执行以下操作:

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. 无论如何,我希望这能解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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