Cannot create and populate list type System.Object.

Jul 26, 2010 at 1:02 PM
Edited Jul 26, 2010 at 1:07 PM

I'm trying to serialise / deserialize a class that has a property of type object:

 

    public class TestObject
    {
        public object Property;
    }

 

This works for ints, strings and dates but seems to have problems with lists : 

 

        [Test]
        public void TestSerializingObjectWithList()
        {
            var testObject = new TestObject {Property = new[] {1, 2, 3}};
            var serialized = Serialize(testObject);
            Console.WriteLine(serialized);
            var deserialized = Deserialize(serialized);

            Assert.AreEqual(testObject.Property, deserialized.Property);
        }

        private string Serialize(object thing)
        {
            var json = new JsonSerializer();

            var sb = new StringBuilder();
            var writer = new JsonTextWriter(new StringWriter(sb));

            json.Serialize(writer, thing);
            return sb.ToString();
        }

        private TestObject Deserialize(string thing)
        {
            var json = new JsonSerializer();

            var reader = new JsonTextReader(new StringReader(thing));
            var filter = json.Deserialize(reader, typeof(TestObject)) as TestObject;
            return filter;
        }

The test successfully serializes the object to :

{"Property":[1,2,3]}

But trying to deserialize this results in an exception:  

System.Exception: Cannot create and populate list type System.Object. 

Any ideas how I can overcome this?  

Thanks, 

Matt

Sep 11, 2010 at 2:03 PM

You can't deserialize a JSON array to an Object. (Your Property property is an object.) If Property were an array, I beleive it would deserialize properly.