我想让 ASP.NET MVC 以 JSON 格式返回存储在 MongoDB 中的文档,但不需要先将其序列化为 .NET 类型。但是,BSONDocument.ToJSON() 返回如下所示的 JSON:
{_id:ObjectId("someid")}
浏览器的 JSON 解析器不喜欢“ObjectId(nnn)”,因此调用失败并出现解析器错误。我能够使用 Regex hack 获得可解析的 JSON:
public ActionResult GetFormDefinitionsJSON()
{
var client = new MongoDB.Driver.MongoClient(ConfigurationManager.ConnectionStrings["mongodb"].ConnectionString);
var db = client.GetServer().GetDatabase("formthing");
var result = db.GetCollection("formdefinitions").FindAll().ToArray();
var sb = new StringBuilder();
sb.Append("[");
var regex = new Regex(@"(ObjectId\()(.*)(\))");
var all = result.Select(x => regex.Replace(x.ToJson(), "$2"));
sb.Append(string.Join(",", all));
sb.Append("]");
return Content(sb.ToString(), "application/json");
}
这将返回可解析的 JSON:
{_id:"someid"}
但它闻起来。没有正则表达式和字符串构建 hackery,有什么方法可以让官方 MongoDB 驱动程序返回可以被浏览器解析的 JSON?或者,我是否在浏览器端遗漏了一些允许 {_id:ObjectId("someid")} 被解析为有效的东西?
最佳答案
你有两个我能想到的选择。
第一个是使用 JavaScript JsonOutputMode
模式。这导致 ID 序列化为 "_id": { "$oid": "51cc69b31ad71706e4c9c14c"}
- 不太理想,但至少它是有效的 Javascript Json。
result.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript })
另一种选择是将结果序列化为一个对象并使用 [BsonRepresentation(BsonType.String)]
属性。这会产生更好的 Json:"_id": "51cc6a361ad7172f60143d97"
;但是,它需要您定义一个类以将其序列化到(这会影响性能)
class Example
{
[BsonId]
[BsonRepresentation(BsonType.String)]
public ObjectId ID { get; set; }
public string EmailAddress { get; set; }
}
// Elsewhere in Code - nb you need to use the GetCollection<T> method so
// that your result gets serialized
var result = database.GetCollection<Example>("users").FindAll().ToArray();
var json = result.ToJson();
有关 JsonOuputModes(Strict、Javascrpt 和 Mongo)之间差异的更多详细信息:
http://docs.mongodb.org/manual/reference/mongodb-extended-json/
关于c# - C# MongoClient 是否可以在不首先序列化为 .NET 类型的情况下用于返回有效的 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17195301/