可以使用C#MongoClient返回有效的JSON而无需先序列化为.NET类型吗?

Dan*_*iel 4 c# asp.net-mvc json mongodb

我想让ASP.NET MVC将存储在MongoDB中的文档作为JSON返回,但不需要先将它序列化为.NET类型.但是,BSONDocument.ToJSON()返回如下所示的JSON:

    {_id:ObjectId("someid")}
Run Code Online (Sandbox Code Playgroud)

浏览器的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");
    }
Run Code Online (Sandbox Code Playgroud)

这将返回可解析的JSON:

   {_id:"someid"}
Run Code Online (Sandbox Code Playgroud)

但它闻起来.有没有办法没有正则表达式和字符串构建hackery来获取官方MongoDB驱动程序返回可以由浏览器解析的JSON?或者,我是否遗漏了浏览器端允许{_id:ObjectId("someid")}被解析为有效的内容?

Sha*_*thy 8

你有两个我能想到的选择.

第一个是使用JavaScript JsonOutputMode模式.这导致ID序列化"_id" : { "$oid" : "51cc69b31ad71706e4c9c14c" }- 不太理想,但至少它是有效的Javascript Json.

result.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript })
Run Code Online (Sandbox Code Playgroud)

另一种选择是将结果序列化为对象并使用该[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();
Run Code Online (Sandbox Code Playgroud)

关于JsonOuputModes(Strict,Javascrpt和Mongo)之间差异的更多细节:

http://docs.mongodb.org/manual/reference/mongodb-extended-json/