so in order to use private setters with Json.Net, the [JsonProperty]
attribute had to be used, however, it seems that private setters don't cause any issue if we use JsonConvert.PopulateObject
,
Example:
If we have Class A that will be serialized
public class Class_A
{
[JsonProperty]
Class_B m_subData = new Class_B("Default data");
}
and one of its members is Class B that has a property with a private setter:
public class Class_B{
public string Data {get;private set;}
public Class_B(string data){
Data = data;
}
}
Then this deserialization attempt will fail and classAObj will have a classB member that contains the "Default data" instead of whatever the Json content actually has.
public class DataManager{
public void DeserializeData(string jsonData){
var classAObj= (Class_A) JsonConvert.DeserializeObject(jsonData, dataType);
}
}
which is expected and we have to add the [JsonProperty]
attribute to class_B properties that has private setters.
What i don't understand is why this works:
public class DataManager{
public void DeserializeData(string jsonData){
var classAObj = (Class_A) Activator.CreateInstance(dataType);
var settings = new JsonSerializerSettings
{
ObjectCreationHandling = ObjectCreationHandling.Replace
};
JsonConvert.PopulateObject(jsonData, classAObj, settings);
}
}
So despite still having private setters in Class_B and NOT having the [JsonProperty]
attribute, the JsonConvert.PopulateObject
will indeed populate the object with the correct data, the only difference is that its an "existing object", but, how is it able to set its private properties without going through the constructor ?
Thank you!