I am using JavaScriptSerializer to serialize and deserialize the properties in my object. Everything works fine during serialization. However, few properties are serialized to default values instead of the actual value assigned to them.
This is my class
[Serializable]
public Class SimpleClass
{
//This property is serialized properly
//But always de-serialized to null
[DefaultValue("null")]
public List<string> Collection { get; }
}
This is the code used for serialization and de-serialization
SimpleClass testObject =new SimpleClass();
testObject.Collection.Add("One");
testObject.Collection.Add("Two");
testObject.Collection.Add("Three");
testObject.Collection.Add("Four");
testObject.Collection.Add("Five");
//Serializing the above object
string serializedString = new JavaScriptSerializer().Serialize(testObject);
//Deserializing the serialized string
testObject = new JavaScriptSerializer().Deserialize<SimpleClass>(serializedString);
However, after de-serialization, the value of testObject.Collection
property is always null
Any property without setter is always de-serialized to default value.
JavaScriptSerializer
internally uses Reflection to serialize and deserialize an object. If setter is not present in a property, then the serializer cannot modify the value of this property. So, it will be initialized with its default value.
In the above code, property Collection does not have a default value so it is assigned null during de-serialization.