Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string to type in object

Tags:

c#

c#-4.0

The code I have to implement takes a posted list of data from an Ajax call from a web page.

I know the object I need to update, but each field/value pair is coming through as string values and not as their proper types.

So I am trying to work out the type of the property, casting the value as the new type and then apply that to the field using reflection.

However I am getting the following error for anything other than strings.

Invalid cast from 'System.String' to 'System.TimeSpan'.

The code I am attempting the conversion in is;

    public void Update<T>(string fieldName, string fieldValue)
    {
        System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
        Type propertyType = propertyInfo.PropertyType;

        var a = Convert.ChangeType(fieldValue, propertyType);
    }

So is the target object.

like image 718
griegs Avatar asked Dec 06 '22 07:12

griegs


2 Answers

There is no absolute answer that works for all types. But, you could use a TypeConverter instead of Convert, it usually works better. For example, there is a TimeSpanConverter:

public void Update<T>(string fieldName, string fieldValue)
{
    System.Reflection.PropertyInfo propertyInfo = typeof(T).GetProperty(fieldName);
    Type propertyType = propertyInfo.PropertyType;

    TypeConverter converter = TypeDescriptor.GetConverter(type);
    if (converter.CanConvertFrom(typeof(string)))
    {
        var a = converter.ConvertFrom(fieldValue, type);
        ...
    }
}
like image 141
Simon Mourier Avatar answered Dec 09 '22 16:12

Simon Mourier


For handling JSON in MVC (and .NET in general) I use JSON.NET. It is included out-of-the-box in the ASP.NET MVC 4 project template and available on NuGet otherwise. Deserializing JSON string content is (generally) as simple as:

JsonConvert.DeserializeObject<Customer>(json);

If the JSON being passed isn't a serialized model, you could create a code model to match the JSON.

If that doesn't work for your scenario, you can try the Convert class which has options for conversion if you know the type:

Convert.ToInt32(stringValue);

Or the ChangeType method if it's dynamic:

Convert.ChangeType(value, conversionType);
like image 36
Steve Andrews Avatar answered Dec 09 '22 15:12

Steve Andrews