object[] TypeNameHandling

Aug 19, 2010 at 12:04 PM

 

Hi! I would like to replace BinnaryFormatter based serialization with Json.NET BSON serialization. Can anything be done to make following test pass? TypeNameHandling.All doesn't help. Thanks!
One more thing. When deserializing to object[] I get exception 'Json object cannot be deserialized to object[]'. I'm not sure if that is desired behavior.
[TestClass]
    public class BsonRemotingTests
    {
        class A
        {
            [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
            public object[] data;
        }

        [TestMethod]
        public void TypeNameHandlingTest()
        {
            JsonSerializer js = new JsonSerializer();

            var a = new A { data = new object[] { 1, "2", "3", new DateTime(), 4, true, false } };
            byte[] data;

            using (var ms = new MemoryStream())
            using (var w = new Newtonsoft.Json.Bson.BsonWriter(ms))
            {
                js.Serialize(w, a);
                data = ms.ToArray();
            }            

            using (var ms = new MemoryStream(data))
            using (var r = new Newtonsoft.Json.Bson.BsonReader(ms))
            {
                var ca = js.Deserialize<A>(r);
                Assert.AreEqual(a.data.Length, ca.data.Length);
                for (var i = 0; i < a.data.Length; i++)
                    Assert.AreEqual(a.data[i].GetType(), ca.data[i].GetType());
            }
        }

    }

 

Coordinator
Aug 19, 2010 at 9:39 PM

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 5:33 AM

Thanks, I figured that out. However, I'm still looking for an answer for my first question.

Aug 20, 2010 at 6:00 AM

I got it. Int, bool and other values cannot include type information, as they are just values, while json objects can be extended with type member.