I using json .NET to deserialize my json string to my model. below is what I am trying to achieve, please advice what is best way ..
When there is no data my response looks like below
json string = "{\"message\":\"SUCCESS\",\"result\":null}"
the result eventually is tied to a view. So when the response is null I would like to intialize my view with default model values. And so would like to call Default constructor on deserialization. Default constructor looks like below.
public ProfileModel()
{
this.DefaultTab = DefaultTabOption.PROFILE;
this.DataLoadPosition = new DataLoadPositionOptionsModel();
this.DataLayout = new DataLayoutOptionsModel();
this.NAData = new NADataOptionsModel();
this.DataTable = new DataDisplayOptionsModel();
}
But when there is data, the reponse looks like below.
{"message":"SUCCESS","result":{"dataLayout":{"vertical":false},"dataLoadPosition":{"cell":"B2","cursorLocation":false},"dataTable":{"decimalPts":1},"defaultTab":"BROWSE","naData":{"custom":"","naDataOption":"FORWARDFILL"}}}
In this case, I would like to call my parameterized constructor so that models are initialized correctly.
Deserialization code:
using (StreamReader reader = new StreamReader(responseStream))
{
var t = JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
return t;
}
Where T is my main Model which initilialises multiple models. Below is the parameterized contructor.
public ProfileModel(DefaultTabOption defaultTabModel,
DataLoadPositionOptionsModel dataLoadPositionOption ,
DataLayoutOptionsModel dataLayoutOptios ,
NADataOptionsModel naDataOptions ,
DataDisplayOptionsModel dataTableOptions)
{
this.DefaultTab = defaultTabModel;
this.DataLoadPosition = dataLoadPositionOption;
this.DataLayout = dataLayoutOptios;
this.NAData = naDataOptions;
this.DataTable = dataTableOptions;
}
What is they best way to deserialize so that default constructor is called when null and parameterized is call when not null. I tried the ConstructorHandling, NullValueHandling but I am not able to achieve desired results.