我正在使用MongoDB C#驱动程序.我有一个BsonDocument,其中包含一些特定于MongoDB的特定类型(例如ObjectID和ISODates)的数据.我想将其转换为有效的通用JSON字符串.换句话说,我不能使用_id: ObjectId(...)或date: ISODate(...)之类的东西,但希望使用_id: "..."和date: "...".基本上,我想将仅MongoDB可以识别的这些特殊类型转换为常规字符串,以便可以更轻松地解析它们.问题在于,像.ToJson()这样的内置函数(另一个StackOverflow答案建议)根本不会将文档转换为有效的JSON,因为它维护了这些特殊类型.我的文档还包含许多级别的数组和子文档,因此,简单的for循环是不够的.避免此问题的转换BsonDocument的最佳方法是什么?我更喜欢内置的东西,而不是手动遍历文档来解决所有问题.
I am working with the MongoDB C# driver. I have a BsonDocument with some data which includes some MongoDB-specific types (like ObjectIDs and ISODates). I want to convert this to a valid general-purpose JSON string. In other words, I can't have something like _id: ObjectId(...) or date: ISODate(...) but would prefer _id: "..." and date: "...". Basically, I want to convert these special types that only MongoDB recognizes to regular strings so they can be parsed more easily. The problem is that a built-in function like .ToJson() (which another StackOverflow answer suggests) doesn't really convert the document to valid JSON at all because it maintains these special types. My document also contains many levels of arrays and sub-documents, so a simple for loop will not suffice. What's the best way to convert a BsonDocument that avoids this problem? I would prefer something built-in rather than manually recursing through the document to fix all the issues.
推荐答案我遇到了同样的事情,您可以通过以下方式获取有效的JSON:
I've ran into the same thing, you can get valid JSON via:
var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict }; JObject json = JObject.Parse(postBsonDoc.ToJson<MongoDB.Bson.BsonDocument>(jsonWriterSettings));但是它将返回类似的内容:
However it will return something like:
{"_id":{"$oid":"559843798f9e1d0fe895c831"}, "DatePosted":{"$date":1436107641138}}我仍在寻找一种方法来使之扁平化.
I'm still trying to find a way to flatten that.
更多推荐
在C#中将MongoDB BsonDocument转换为有效的JSON
发布评论