Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling MongoDB's ISODate() when attempting to parse a serialized JSON string

I'm using MongoDB via the official C# driver with an ASP.NET MVC web site.

I have the following C# model:

public class Contact
{
    public ObjectId Id { get; set; }
    public string Name { get; set; }
    public DateTime DateAdded { get; set; }
}

Which, when pulled from MongoDB and serialized into a JSON string via MVC looks like:

{
    "_id"  : ObjectId("52eaad4839b60812fca4bf28"),
    "Name": "Joe Blow",
    "DateAdded" : ISODate("2014-01-30T19:51:35.977Z")
}

When I attempt to convert this from a JSON string to a Javascript object on the browser via JSON.parse(), I get the following error:

Uncaught SyntaxError: Unexpected token I

This is because ISODate(...) is not valid JSON

ObjectId() is also not valid JSON, but the way I'm handling that is to simply perform a string.replace() on the JSON string prior to parsing it on the client. I considered doing the same for ISODate() but it feels a little too hacky.

Is there something I can do without resorting to regular expressions on the client side? Perhaps something from the MongoDB driver?

like image 711
Chad Levy Avatar asked Jan 30 '14 20:01

Chad Levy


1 Answers

I think you need to tweak your JSON serializer a bit more. Try this:

var jsonWriterSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
Console.WriteLine(document.ToJson(jsonWriterSettings));
like image 177
Neil Lunn Avatar answered Oct 12 '22 07:10

Neil Lunn