Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically convert object based on property type

Tags:

c#

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;
    }
like image 851
joelforsyth Avatar asked Oct 23 '25 17:10

joelforsyth


2 Answers

You could do it by using Convert.ChangeType like this:

property.SetValue(item, Convert.ChangeType(valueToConvert, property.PropertyType));
like image 175
Simon Karlsson Avatar answered Oct 25 '25 07:10

Simon Karlsson


See: Generic type conversion FROM string

TConverter.ChangeType<T>(StringValue);  

public static class TConverter
{
    public static T ChangeType<T>(object value)
    {
        return (T)ChangeType(typeof(T), value);
    }
    public static object ChangeType(Type t, object value)
    {
        TypeConverter tc = TypeDescriptor.GetConverter(t);
        return tc.ConvertFrom(value);
    }
    public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter
    {

        TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));
    }
}
like image 23
Paul Avatar answered Oct 25 '25 08:10

Paul