在MongoDB中OjbectId 类型Json序列化反序列化会出错,可以通过以下两种方式解决
1、最简单粗暴的方法,从新定一个一个业务主键比如key,这样的话等于之前的_id不起作用了
2、使用JsonConverter
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."); } } }
在ObjectId字段上加一行代码即可
[JsonConverter(typeof(ObjectIdConverter))] public string _id { get; set; }
3、通过Ignore,一种很有技巧性的写法
[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; } }