Search code examples
jsonlistwindows-phone-7activatordeserialization

How to use Activator.CreateInstance with List<T> when Deserialize json with DataContractJsonSerializer


I'm deserializing this json string:

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

The class which represents the items is:

[DataContract]
public class MyClass 
{

        public MyClass() {
            this._dtcreate = new DateTime();
        }

        private int _id;
        [DataMember(Name = "id")]
        public int Id {get;set;}

        private DateTime _dtcreate;
}

Note that in the default constructor of MyClass I set a default value for "_dtcreate".

So, I'm using this code to Deserialize json into a Array of T:

 public static T[] DeserializeArray<T>(string json)
    {
        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T[]));
        MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
        T[] gType = (T[])ser.ReadObject(ms);
        return gType;
    }

When I deserialize a json string I not found in my deserialized array the property "_dtcreate" evalued.

I think DataContractJsonSerializer doesn't use the default constructor of MyClass.

Can I use the

T obj = Activator.CreateInstance<T>();

to create an instance for all object belonging to the array "gType" to make me ensure that all objects of my list deserialiced are created with the dafault constructor of my T class ?

Thank you so much!


Solution

  • DataContract serializers will not run constructors.

    Instead, you should put your logic into an [OnDeserializing] method.