将Newtosoft JObject直接转换为BsonDocument [英] Convert Newtosoft JObject directly to BsonDocument

查看:242
本文介绍了将Newtosoft JObject直接转换为BsonDocument的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下示例尝试将JObject转换为BsonDocument https: //www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter已过时,所以我使用BsonDataWriter)

Try to convert JObject to BsonDocument using this example https://www.newtonsoft.com/json/help/html/WriteJTokenToBson.htm (BsonWriter obsolete, so I use 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,避免序列化为字符串和字符串解析

UPD: I have a JObject, and I want to convert it directly to BSONDocument, avoid serialization to string and string parsing

推荐答案

您可以使用Newtonsoft的

You can write a JObject to a BSON stream using Newtonsoft's BsonDataWriter like so:

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;

然后,您可以使用MongoDB .NET驱动程序解析写入的流,如下所示:

Then, you can parse the written stream with the MongoDB .NET Driver like so:

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

然后像这样检查创建的文档的有效性:

And check the validity of the created document like so:

// 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

注意:

  • When you do var bsonData = writer.ToBsonDocument(); you are actually serializing Newtonsoft's BsonDataWriter using the MongoDB extension method BsonExtensionMethods.ToBsonDocument(), which explains the strange contents of the bsonData document in your test code.

相反,可以从刚写入的流中获取序列化的BSON.

Instead, the serialized BSON can be obtained from the stream to which it was just written.

如果您要立即重新读取流,则可以通过设置 JsonWriter.CloseOutput = false .写入后将流位置设置为0.

If you are going to immediately re-read the stream, you can keep it open by setting JsonWriter.CloseOutput = false. Set the stream position to 0 after writing.

虽然您的方法避免了序列化和解析JSON字符串的开销,但您仍在序列化和反序列化BSON二进制流.

While your approach avoids the overhead of serializing and parsing a JSON string, you are still serializing and deserializing a BSON binary stream.

演示小提琴此处.

这篇关于将Newtosoft JObject直接转换为BsonDocument的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆