MongoDB数据实体中的ObjectId序列化成json的一个小坑

释放双眼,带上耳机,听听看~!

很多时候我们都需要对实体对象进行序列化与反序列化,而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.");
            }
        }
    }

人已赞赏
瞎捯饬随笔

安卓浏览安装油猴插件详解

2018-12-10 12:18:16

瞎捯饬随笔黑科技

Vip视频解析插件使用说明

2018-12-10 12:23:07

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索