如何使用.net格式化对象ID和日期以在json序列化输出中正确显示?如何使用.net格式化对象ID和日期以正确显示json序列化的mongodb数据?
return Json(result, JsonRequestBehavior.AllowGet);
,这里是输出,我得到
{
"_id": {
o "Timestamp": 1321487136,
o "Machine": 5156,
o "Pid": -4604,
o "Increment": 78,
o "CreationTime": "/Date(1321487136000)/"
},
"start": "/Date(1321487094000)/",
"end": "/Date(1638039600000)/",
}
我想的JSON看起来像这样
{
"_id":"4e483da1e517801b09000004",
"end":"2012-12-30T05:00:00.000Z",
"start":"2011-08-14T17:26:57.000Z"
}
通过以下的建议,阅读,得到了它与工作以下
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" };
}
的建议的字符串,让它工作 – MonkeyBonkey