bson has some problem,help!!!

Aug 18, 2010 at 2:15 AM

it is a well job,but it still hava bug when i use bson to serilaze new [] { 1, 2, 3, 5 } ,and i deserilaze it is will throw this exception Cannot deserialize JSON object into type 'System.Int32[]'.。

 

我在补充一下吧,用中文,当我用bson序列号一个int数组时,例如new [] { 1, 2, 3, 5 },没有问题,但当我反序列化时会报错:Cannot deserialize JSON object into type 'System.Int32[]. 我的反序列化方法是这样写的: using (var ms = new MemoryStream(bson, index, count)) using (var bsonReader = new BsonReader(ms)) { var serializer = new JsonSerializer { ObjectCreationHandling = ObjectCreationHandling.Replace, MissingMemberHandling = MissingMemberHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Ignore }; return (T) serializer.Deserialize(bsonReader, typeOfT); }

Coordinator
Aug 19, 2010 at 11:19 AM

You need to set ReadRootValueAsArray on BsonReader. It is a limitation of BSON that it can't automatically detect the root containers type.

Aug 20, 2010 at 9:57 AM

        /// <summary>
        /// 反序列化
        /// </summary>
        /// <typeparam name="T">要反序列化的类型</typeparam>
        /// <param name="bson">byte数组</param>
        /// <param name="typeOfT">反序列化的类型</param>
        /// <param name="index">开始位置</param>
        /// <param name="count">数量</param>
        /// <returns>T</returns>
        public static T DeserializeJosn<T>(this byte[] bson, Type typeOfT, int index, int count)
        {
            using (var ms = new MemoryStream(bson, index, count))
            using (var bsonReader = new BsonReader(ms))
            {
                var serializer = new JsonSerializer
                {
                    ObjectCreationHandling = ObjectCreationHandling.Replace,
                    MissingMemberHandling = MissingMemberHandling.Ignore,
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                };

                return (T)serializer.Deserialize(bsonReader, typeOfT);
            }
            //return JsonConvert.DeserializeObject<T>(Encoding.UTF8.GetString(bson, index, count));
        }

 

As you see,this is a common method to Deserialize any object,if i set ReadRootValueAsArray on BsonReader ,the other type that not array are not work!!

as i know ,Mongodb is base bson,Maybe we can learn from Mongodb.

Coordinator
Aug 20, 2010 at 12:03 PM

I know the BSON spec and it doesn't specify at a root level whether the data structure is a name/value object or a list.

http://groups.google.com/group/bson/browse_thread/thread/6fb25abfc5e0dafa

If you really want a generic method then you could do some reflection on whether the object being deserialized is a collection as a test to decide if ReadRootValueAsArray should be set.