Is it possible to use C # MongoClient to return valid JSON without pre-serialization to a .NET type?

I would like ASP.NET MVC to return the document stored in MongoDB as JSON, but it does not need to serialize it to .NET first. However, BSONDocument.ToJSON () returns a JSON that looks like this:

{_id:ObjectId("someid")} 

The browser JSON parser does not like "ObjectId (nnn)", and therefore the call fails with a parser error. I can get JSON with parsing using the Regex handle:

  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"); } 

This returns JSON parsing:

  {_id:"someid"} 

But it smells. Is there a way, without using regular expression and string building hacking, to force the official MongoDB driver to return JSON that can be parsed by the browser? Alternatively, did I skip something on the browser side to allow {_id: ObjectId ("someid")} to be considered valid?

+4
source share
1 answer

You have two options that I can think of.

The first is to use JsonOutputMode JavaScript JsonOutputMode . This results in the serialization of the ID to "_id" : { "$oid" : "51cc69b31ad71706e4c9c14c" } - not quite perfect, but at least it's valid Javascript Json.

 result.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.JavaScript }) 

Another option is to serialize the results into an object and use the [BsonRepresentation(BsonType.String)] attribute. This leads to a significantly nicer Json: "_id" : "51cc6a361ad7172f60143d97" ; however, this requires a class to be serialized (this may affect performance)

 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(); 

More details on the differences between JsonOuputModes (Strict, Javascrpt and Mongo):

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

+8
source

Source: https://habr.com/ru/post/1487071/


All Articles