我有一个包含JSON的字符串。我对这个JSON唯一了解的是它是有效的。如何将此字符串转换为BSON?
答案 0 :(得分:9)
BsonWriter
的{{1}}已过时。
您需要添加名为Newtonsoft.Json
的新nuget-package(仅搜索Json.NET BSON
)并使用newtonsoft.json.bson
和BsonDataWriter
代替BsonDataReader
BsonWriter
:
BsonReader
答案 1 :(得分:4)
我认为这会为你做到这一点
MongoDB.Bson.BsonDocument BSONDoc
= MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>(json);
您还可以查看Serialize to BSON和C# - Converting JSON string to BSON document
答案 2 :(得分:2)
https://www.nuget.org/packages/Newtonsoft.Json
PM&GT;安装包Newtonsoft.Json -Version 7.0.1
using Newtonsoft.Json.Bson;
using Newtonsoft.Json;
class Program
{
public class TestClass
{
public string Name { get; set; }
}
static void Main(string[] args)
{
string jsonString = "{\"Name\":\"Movie Premiere\"}";
var jsonObj = JsonConvert.DeserializeObject(jsonString);
MemoryStream ms = new MemoryStream();
using (BsonWriter writer = new BsonWriter(ms))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(writer, jsonObj);
}
string data = Convert.ToBase64String(ms.ToArray());
Console.WriteLine(data);
}
}
答案 3 :(得分:2)
看哪!有一种更简单的方法:
BsonDocument doc = BsonDocument.Parse("{\"your\": \"json\", \"string\": \"here\"}");
答案 4 :(得分:2)
在我的项目中使用json
时,我注意到将json
转换为bson
文档的方法很简单。
string json = "{\"Name\":\"Movie Premiere\"}";
BsonDocument document = BsonDocument.Parse(json);
现在你可以在任何地方使用document
作为bson。
注意 - 我正在使用此document
插入MongoDb
数据库。
希望这会对你有所帮助。