我正在使用 MongoDB,并且有一个带有 mongodb ObjectId 的对象。 当我使用 .NET Json() 方法对其进行序列化时,一切都很好(但日期很糟糕!)
如果我使用 JSON.NET 序列化程序尝试此操作,它会在尝试序列化 ObjectID 时给我一个 InvalidCastException
任何想法发生了什么以及如何解决这个问题?
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.
如果您将 Controller 方法更改为使用 .NET 附带的序列化程序,它可以正常工作(但是,这个给出了丑陋的日期,蓝光)
public JsonResult NiceJsonPlease()
{
var q = new TestClass();
q.id = new ObjectId();
q.test = "just updating this";
return Json(q, JsonRequestBehavior.AllowGet);
}
最佳答案
你可以使用.NET字符串类型来代替ObjectId,你只需要用BsonRepresentation来装饰它。如果您使用 BsonDateTime,您将遇到相同的转换问题。这是我项目中使用这些装饰器的域类。
public class DocumentMetadata
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public string FullName { get; set; }
[BsonDateTimeOptions(Kind = DateTimeKind.Utc)]
public DateTime DownloadTime { get; set; }
}
https://stackoverflow.com/questions/16651776/
相关文章:
mongodb - 异常 : can't convert from BSON type EOO to
mongodb - 在 MongoDB shell 查询中获取 "data from collect
mongodb - 无法使用 --db 创建备份 mongodump。身份验证失败
python - 文档中的 Mongoengine creation_time 属性
mongodb - 将 PouchDB 与 MongoDB 一起使用
regex - 如何使用 mongoose find 获取包含部分字符串的所有值?
mongodb - 复制/克隆 mongodb 数据库及其数据