我需要帮助,我想将数据从Json File添加到MongoDb,我使用此代码,但它给我一个错误:“ FormatException”:无法从BsonType'Array'反序列化'BsonDocument'。” :( :( this is my code
**static async Task MainAsync()
{
var connectionString = "mongodb://localhost:27017";
var client = new MongoClient(connectionString);
IMongoDatabase database = client.GetDatabase("test");
string json = File.ReadAllText("D:\\Test.json");
//MessageBox.Show(json);
var document = new BsonDocument();
BsonDocument doc = BsonDocument.Parse(json);
document.Add(BsonDocument.Parse(json));
BsonSerializer.Deserialize<BsonDocument>(json);
//BsonDocument document = BsonDocument.Parse(json.ToString());
var collection = database.GetCollection<BsonDocument>("test_collection");
await collection.InsertOneAsync(document);**
这是我用来创建JSON文件的代码: 公共布尔WriteJason(DataTable dt,字符串路径) { 尝试 {
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, string>> rows = new List<Dictionary<string, string>>();
Dictionary<string, string> row = null;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, string>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName.Trim().ToString(), Convert.ToString(dr[col]));
}
rows.Add(row);
}
string jsonstring = serializer.Serialize(rows);
using (var file = new StreamWriter(path, false))
{
file.Write(jsonstring);
file.Close();
file.Dispose();
}
return true;
}
catch { return false; }
}
答案 0 :(得分:1)
您需要执行的代码要少得多,这应该足够了:
string json = File.ReadAllText("D:\\Test.json");
BsonDocument doc = BsonDocument.Parse(json);
var collection = new MongoClient("mongodb://localhost:27017").GetDatabase("test").GetCollection<BsonDocument>("test_collection");
await collection.InsertOneAsync(doc);
如果这不起作用,则您需要在此处发布的JSON文件有问题。