I am trying to typecast object inside dynamic object to a type which is passed as a parameter. I searched but couldn't find any specific solution to the issue.
Firstly the structure of the class is as under:
[DataContract(Namespace = "")]
public class Resultset
{
[DataMember]
public DataTable dt { get; set; }
[DataMember]
public string status { get; set; }
[DataMember]
public string res { get; set; }
[DataMember]
public object retClass { get; set; }
public Resultset()
{
dt = new DataTable();
status = string.Empty;
res = string.Empty;
}
}
The retClass object in Resultset holds any dynamic classtype structure. Now the below method typecasts the API call result in above class to Resultset class at client's end:
public string sanitizeData(string apiResponse, Type classType)
{
Resultset rs = new Resultset();
dynamic dSerializedData = null;
try
{
Convert.ChangeType(rs.retClass, classType);
dSerializedData = JsonConvert.DeserializeObject<dynamic>(apiResponse);
rs.retClass = Convert.ChangeType(dSerializedData.retClass.ToObject<typeof(classType)>(), classType);
rs.res = dSerializedData.res;
rs.status = dSerializedData.status;
return JsonConvert.SerializeObject(rs);
}
catch (Exception)
{
throw;
}
}
The api response is getting deserialized to dynamic type easily. But Since the retClass can be of anyClass type, I have to pass the type as a parameter. Exception arises at
rs.retClass = Convert.ChangeType(dSerializedData.retClass.ToObject<typeof(classType)>(), classType);
when I use the ToObject<typeof(classType)>()
method, here I am using the variable as a type which is not permitted.
The above code works fine when classType
is replaced with the name of the class. But since retClass
object itself is dynamic, I need a generic solution to the issue.
Please help me with this specific scenario.