How do I format object ids and dates to show up correctly in the json serialized output using .net?
return Json(result, JsonRequestBehavior.AllowGet);
and here is the output that I get
{
"_id": {
o "Timestamp": 1321487136,
o "Machine": 5156,
o "Pid": -4604,
o "Increment": 78,
o "CreationTime": "/Date(1321487136000)/"
},
"start": "/Date(1321487094000)/",
"end": "/Date(1638039600000)/",
}
I’d like the json to look like this
{
"_id":"4e483da1e517801b09000004",
"end":"2012-12-30T05:00:00.000Z",
"start":"2011-08-14T17:26:57.000Z"
}
Reading through the advice below, got it working with the following
public class MongoSimpleIdConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType == typeof(MongoDB.Bson.ObjectId);
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return new MongoDB.Bson.ObjectId((string)existingValue);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
writer.WriteValue(((MongoDB.Bson.ObjectId)value).ToString());
}
}
[HttpGet]
public ContentResult Index()
{
var result = JsonConvert.SerializeObject(svc.GetTasks(), new MongoSimpleIdConverter(), new IsoDateTimeConverter());
return new ContentResult { Content = result, ContentType = "application/json" };
}
Huh, interesting, I was sure it was going to be a breeze, but it doesn’t seem like there’s a simple answer like “Write a converter and plug it with an attribute”.
I would recommend using a 3rd party like Json.net (which supports custom converters) and staying away from the built-in method.
I once wrote this code to handle the same problem with id serialization in the unofficial mongo driver –