4

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;
    }
joelforsyth
  • 836
  • 1
  • 11
  • 28
  • 1
    AutoMapper has a an interface for a `TypeConverter`, does it help? https://github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters – Eris Aug 31 '15 at 19:12

2 Answers2

14

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

property.SetValue(item, Convert.ChangeType(valueToConvert, property.PropertyType));
Simon Karlsson
  • 4,090
  • 22
  • 39
3

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)));
    }
}
Community
  • 1
  • 1
Paul
  • 5,700
  • 5
  • 43
  • 67