很多时候我们都需要对实体对象进行序列化与反序列化,而ObjectId类型,只能用mongo的驱动以bson格式来序列化,但我们对外的交互,一般是json格式.
有两种解决方案:
1.自己写一个json.net的ObjectIdConverter来针对ObjectId,适用于json.net
2.增加string类型的中间变量IdStr ,优点是适用于所有情况,比如mvc自带的序列化工具等
[TestClass] public class MongoTest { [TestMethod()] public void Temp1() { var entity = new MyEntity() { Id = new ObjectId("555afe4204cbee061cc31b6f"), Name = "ZhangSan" }; var str = JsonConvert.SerializeObject(entity);//{"Id":"555afe4204cbee061cc31b6f","Name":"ZhangSan"} var entity1 = JsonConvert.DeserializeObject(str); } [TestMethod()] public void Temp2() { var entity = new MyEntity2() { Id = new ObjectId("555afe4204cbee061cc31b6f"), Name = "ZhangSan" }; var str = JsonConvert.SerializeObject(entity); //{"IdStr":"555afe4204cbee061cc31b6f","Name":"ZhangSan"} var entity2 = str.FromJson(); } [TestMethod()] public void Temp3() { var entity = new MyEntity3() { Id = new ObjectId("555afe4204cbee061cc31b6f"), Name = "ZhangSan" }; var str = JsonConvert.SerializeObject(entity); //{"Id":"555afe4204cbee061cc31b6f","Name":"ZhangSan"} var entity2 = str.FromJson(); } } public class MyEntity { public virtual ObjectId Id { get; set; } public virtual string Name { get; set; } } public class MyEntity2 : MyEntity { [JsonIgnore] public override ObjectId Id { get; set; } [BsonIgnore] public string IdStr { get { return Id.ToString(); } set { ObjectId id; ObjectId.TryParse(value, out id); Id = id; } } } public class MyEntity3 : MyEntity { [JsonConverter(typeof(ObjectIdConverter))] public override ObjectId Id { get; set; } } public class ObjectIdConverter : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(ObjectId); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { if (reader.TokenType != JsonToken.String) { throw new Exception( String.Format("Unexpected token parsing ObjectId. Expected String, got {0}.", reader.TokenType)); } var value = (string)reader.Value; return String.IsNullOrEmpty(value) ? ObjectId.Empty : new ObjectId(value); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { if (value is ObjectId) { var objectId = (ObjectId)value; writer.WriteValue(objectId != ObjectId.Empty ? objectId.ToString() : String.Empty); } else { throw new Exception("Expected ObjectId value."); } } }