I have a JObject that that I am deserializing from a JSON string from an HTTP post that represents a custom object, Adjuster.
I then merge that object with what already exists in the database to create the updated object. I am doing this with reflection looping through the properties and assigning them where the property names match.
My issue comes up that the JValue can't be implicitly converted to the destination type, I have to manually convert it. Is there a way I can dynamically convert objects? I can get get the type that it will need to be converted to.
Here is my Model Binder:
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
JObject jsonObj = JsonConvert.DeserializeObject(actionContext.Request.Content.ReadAsStringAsync().Result) as JObject;
Adjuster dbAdjuster = new Adjuster();
Type adjType = dbAdjuster.GetType();
PropertyInfo[] props = adjType.GetProperties();
dbAdjuster = AdjusterFactory.GetAdjuster(Convert.ToInt32(jsonObj["ID"].ToString()));
foreach (var prop in jsonObj.Properties() )
{
foreach (PropertyInfo info in props)
{
if (prop.Name == info.Name && prop.Name != "ID")
{
if (info.GetValue(dbAdjuster) is string)
{
info.SetValue(dbAdjuster, Convert.ToString(prop.Value));
break;
}
//continue for every type
}
else
{
break;
}
}
}
bindingContext.Model = dbAdjuster;
return true;
}