简体   繁体   English

如何使用C#将现有Json文件中的数据插入MongoDb?

[英]how to insert data from existing Json File To MongoDb With c#?

I Need Help , I wanna add data From Json File to MongoDb , i use this code but it give me an error : "FormatException : Cannot deserialize a 'BsonDocument' from BsonType 'Array'." 我需要帮助,我想将数据从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);**

And this is th code that i use it to create the JSON file : public bool WriteJason(DataTable dt, string path) { try { 这是我用来创建JSON文件的代码:public bool WriteJason(DataTable dt,string path){试试{

            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; }
    }

You need a lot less code to do that, this should be enough: 您只需执行更少的代码即可,这应该足够了:

 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);

If that doesn't work then something is wrong with your JSON file which you would need to post here. 如果这不起作用,则您需要在此处发布的JSON文件有问题。

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

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