使用Rabbitmq.client反序列化包含Mongo.Bson.ObjectId属性实体类时抛异常

    
原因分析:
   队列中存储的objectId属性是字符串,反序列化字符串转换成objectid类型时报错
 
 
解决方法:
   1、定义ObjectIdConverter属性类,反序列化时将字符串转换成ObjectId
   
  class ObjectIdConverter : JsonConverter
    {
        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            serializer.Serialize(writer, value.ToString());
        }

        /// <summary>
        //  反序列化时将字符串转换成ObjectId类型
        /// </summary>
        /// <param name="reader"></param>
        /// <param name="objectType"></param>
        /// <param name="existingValue"></param>
        /// <param name="serializer"></param>
        /// <returns></returns>
        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
           return new ObjectId(serializer.Deserialize(reader).ToString());
        }

        public override bool CanConvert(Type objectType)
        {
            return typeof(ObjectId).IsAssignableFrom(objectType);
        }
    }

 

   2、将该属性类应用到ObjectId属性上
     [BsonId]
        [JsonConverter(typeof(ObjectIdConverter))]
        public ObjectId Id { get; set; }

 

 



posted @ 2015-05-15 11:59    阅读(1133)  评论(0编辑  收藏  举报