在C#中将MongoDB BsonDocument转换为有效的JSON

编程入门 行业动态 更新时间:2024-10-26 22:19:55
本文介绍了在C#中将MongoDB BsonDocument转换为有效的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在使用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

本文发布于:2023-10-30 07:54:33,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1542241.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   中将   BsonDocument   MongoDB   JSON

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!