I am playing around with MongoDB and have an object with a mongodb ObjectId on it. When I serialise this with the .NET Json() method, all is good (but the dates are horrible!)
If I try this with the JSON.NET serialiser it gives me an InvalidCastException when trying to serialise the ObjectID
any ideas whats happening and how I can fix this?
using MongoDB.Driver;
using MongoDB.Bson;
using Newtonsoft.Json;
//this is a route on a controller
public string NiceJsonPlease()
{
var q = new TestClass();
q.id = new ObjectId();
q.test = "just updating this";
return JsonConvert.SerializeObject(q);
}
//simple test class
class TestClass
{
public ObjectId id; //MongoDB ObjectID
public string test = "hi there";
}
Exception Details: System.InvalidCastException: Specified cast is not valid.
If you change the controller method to use the serializer that ships with .NET, it works ok (but, this one gives ugly dates, blugh)
public JsonResult NiceJsonPlease()
{
var q = new TestClass();
q.id = new ObjectId();
q.test = "just updating this";
return Json(q, JsonRequestBehavior.AllowGet);
}