c# mongodb convert between list and json
时间: 2024-03-02 09:52:41 浏览: 108
To convert a list to JSON in C# using MongoDB, you can use the `ToJson` method provided by the MongoDB driver. Here's an example code snippet:
```
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
var list = new List<string> { "item1", "item2", "item3" };
var json = list.ToJson(new MongoDB.Bson.IO.JsonWriterSettings { OutputMode = MongoDB.Bson.IO.JsonOutputMode.Strict });
Console.WriteLine(json);
```
To convert JSON to a list, you can use the `DeserializeObject` method provided by the Newtonsoft.Json library. Here's an example code snippet:
```
using MongoDB.Bson;
using MongoDB.Driver;
using Newtonsoft.Json;
var json = @"['item1', 'item2', 'item3']";
var list = JsonConvert.DeserializeObject<List<string>>(json);
foreach (var item in list)
{
Console.WriteLine(item);
}
```
阅读全文