在 C# 中将 MongoDB BsonDocument 转换为有效的 JSON [英] Convert MongoDB BsonDocument to valid JSON in C#

查看:36
本文介绍了在 C# 中将 MongoDB BsonDocument 转换为有效的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 MongoDB C# 驱动程序.我有一个带有一些数据的 BsonDocument,其中包括一些 MongoDB 特定的类型(如 ObjectIDs 和 ISODates).我想将其转换为有效的通用 JSON 字符串.换句话说,我不能有像 _id: ObjectId(...)date: ISODate(...) 之类的东西,但更喜欢 _id:..."日期:...".基本上,我想将这些只有 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.

推荐答案

MongoDB.Bson (2.5+) 支持在 BsonValues 和 .Net 对象之间进行映射.BsonTypeMapper 类

MongoDB.Bson (2.5+) has support to map between BsonValues and .Net objects. BsonTypeMapper Class

将 BsonValue(或 BsonDocument)映射到 .Net 对象使用

var dotNetObj = BsonTypeMapper.MapToDotNetValue(bsonDoc);

然后您可以使用您选择的序列化库.例如,

You can then use your choice of serialization library. For example,

JsonConvert.SerializeObject(dotNetObj);

如果你有一个 BsonDocument 列表

var dotNetObjList = bsonDocList.ConvertAll(BsonTypeMapper.MapToDotNetValue);

这篇关于在 C# 中将 MongoDB BsonDocument 转换为有效的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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