尝试使用此示例JObject
将BsonDocument
转换为https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm(BsonWriter
已过时,所以我使用BsonDataWriter
)
var jObject = JObject.Parse("{\"name\":\"value\"}");
using var writer = new BsonDataWriter(new MemoryStream());
jObject.WriteTo(writer);
var bsonData = writer.ToBsonDocument();
Console.WriteLine(bsonData.ToJson());
输出:
{ "CloseOutput" : true, "AutoCompleteOnClose" : true, "Formatting" : 0, "DateFormatHandling" : 0, "DateTimeZoneHandling" : 3, "StringEscapeHandling" : 0, "FloatFormatHandling" : 0, "DateFormatString" : null
, "Culture" : { "Name" : "", "UseUserOverride" : false }, "DateTimeKindHandling" : 1 }
预期输出是:
{"name": "value"}
我该如何解决?
UPD:我有一个JObject,我想将其直接转换为BSONDocument,避免序列化为字符串和字符串解析
您可以像这样使用Newtonsoft的JObject
将BsonDataWriter
写入BSON流:
BsonDataWriter
然后,您可以使用MongoDB .NET驱动程序解析写入的流,如下所示:
var json = "{\"name\":\"value\"}";
var jObject = JObject.Parse(json);
using var stream = new MemoryStream(); // Or open a FileStream if you prefer
using (var writer = new BsonDataWriter(stream) { CloseOutput = false })
{
jObject.WriteTo(writer);
}
// Reset the stream position to 0 if you are going to immediately re-read it.
stream.Position = 0;
并像这样检查创建的文档的有效性:
// Parse the BSON using the MongoDB driver
BsonDocument bsonData;
using (var reader = new BsonBinaryReader(stream))
{
var context = BsonDeserializationContext.CreateRoot(reader);
bsonData = BsonDocumentSerializer.Instance.Deserialize(context);
}
注意:
当您执行// Verify that the BsonDocument is semantically identical to the original JSON.
// Write it to JSON using the MongoDB driver
var newJson = bsonData.ToJson();
Console.WriteLine(newJson); // Prints { "name" : "value" }
// And assert that the old and new JSON are semantically identical
Assert.IsTrue(JToken.DeepEquals(JToken.Parse(json), JToken.Parse(newJson))); // Passes
时,您实际上是使用MongoDB扩展方法var bsonData = writer.ToBsonDocument();
将序列化Newtonsoft的BsonDataWriter
序列化,该方法在您的测试代码中解释了BsonExtensionMethods.ToBsonDocument()
文档的奇怪内容。
相反,可以从刚写入的流中获取序列化的BSON。
如果要立即重新读取流,则可以通过设置BsonExtensionMethods.ToBsonDocument()
使其保持打开状态。写入后将流位置设置为bsonData
。
虽然您的方法避免了序列化和解析JSON字符串的开销,但您仍在序列化和反序列化BSON二进制流。
如果已经有了json字符串,则可以简单地在其中创建一个bson文档