无法反序列化' BsonDocument'来自BsonType' Array'

时间:2016-12-19 17:39:04

标签: c# json mongodb

我在尝试将json字符串解析为BsonDocument时遇到此错误。

C#代码是:

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

虽然最后一个C#代码适用于单个文档:

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

我收到异常无法反序列化&#39; BsonDocument&#39;解析json数组文档时从BsonType&#39; Array&#39;

[
 {
  "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"
    }
          ]
  }
]

关于如何用多个元素解析json的任何想法?提前谢谢。

1 个答案:

答案 0 :(得分:1)

您可以直接使用BsonArraySerializer

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