This project has moved and is read-only. For the latest updates, please go here.

Cannot create and populate list type System.Object.

Jul 26, 2010 at 2:02 PM
Edited Jul 26, 2010 at 2: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 : 


        public void TestSerializingObjectWithList()
            var testObject = new TestObject {Property = new[] {1, 2, 3}};
            var serialized = Serialize(testObject);
            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 :


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?  



Sep 11, 2010 at 3: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.