Reputation: 3491
I have a function that receive a dynamic object and a type as string. I would like to cast the object to the type I have in my string.
public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
switch (ruleType)
{
case "Increase_budget":
ConvertToAutomaticRule(typeof(IncreaseBudgetRule), ref automaticRuleObject);
break;
}
}
private void ConvertToAutomaticRule<T>(Type type, ref dynamic ruleObject)
{
var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
var json = serializer.Serialize(ruleObject);
var c = serializer.Deserialize<type>(json);
}
The class I am trying to convert to:
public class IncreaseBudgetRule
{
public string automaticRuleName { get; set; }
public string givePrioity { get; set; }
}
I have many rules types so I want that function to receive a type and a object and will return an object of the type I sent in the function. How can I accomplish that?
Upvotes: 1
Views: 2436
Reputation: 3283
You don't need the type in your ConvertToAutomaticRule-Method. You defined there a generic paramter which you can use as the type of the outcome. As the Deserialize-Method also accepts a generic Argument you can rewrite your methods like this:
public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
switch (ruleType)
{
case "Increase_budget":
ConvertToAutomaticRule<IncreaseBudgetRule>(ref automaticRuleObject);
break;
}
}
private void ConvertToAutomaticRule<T>(ref dynamic ruleObject)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(ruleObject);
var c = serializer.Deserialize<T>(json);
}
Edit (returning instead of using ref):
You can also use the generic parameter to set is as return type.
public void PostAutomaticRule(dynamic automaticRuleObject, string ruleType)
{
switch (ruleType)
{
case "Increase_budget":
var increasedBudgetRule = ConvertToAutomaticRule<IncreaseBudgetRule>(automaticRuleObject);
break;
}
}
private T ConvertToAutomaticRule<T>(dynamic ruleObject)
{
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(ruleObject);
return serializer.Deserialize<T>(json);
}
Upvotes: 3
Reputation: 1703
try to change your generics to interfaces and that way you can do something like:
var JsonSerializerSettings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.Auto };
var deserializedObject = JsonConvert.DeserializeObject<IYourAutoSerializedObject>(automaticRuleObject.ToString(), JsonSerializerSettings);
Upvotes: 0