Daniel

Daniel

  • NA
  • 1
  • 0

Deserialize from method information in .NET C#

Sep 13 2007 3:39 AM
I am trying to get around AJAX being disabled for our customers in Internet Explorer 6.   I can override the JavaScript events and pass the serialized objects to the server via an iframe.  This is working fine.

I now want to Deserialize the JavaScript object, and pass these parameters to a .NET method.

I have the name of the method as a string, and the JavaScript object.

Using Reflection I want to loop through the parameters of the method and Deserialize each JavaScript object to the correct type.

For example I want to achieve this:

Person opPerson = opSerializer.Deserialize<Person>(opInput);

but where Person is the data type of a parameter of a method, i.e. replace Person with a variable and please don't suggest a large switch statement!

The following example works for methods with multiple int and string parameters:

string zpService = Request["Service"].ToString();
string zpData = Request["_data"].ToString();
string[] zpDataSplit = zpData.Split(',');
string[] zpItemSplit;

DataService opDataService; // Data Service is a Web Service Class
opDataService = new DataService();

JavaScriptSerializer opSerializer = new JavaScriptSerializer();

ParameterCollection opParamCollection = new ParameterCollection();
Parameter opParam;

ParameterInfo[] opParamInfo = opDataService.GetType().GetMethod(zpService).GetParameters();
int lpParamCount = opParamInfo.Length;

Dictionary<string, object> opDictionary;
opDictionary = (Dictionary<string, object>)opSerializer.DeserializeObject(zpData);

Object[] opObjects = new Object[opDictionary.Count];
int lpLoop = 0;

KeyValuePair<string,object> opKVP;

foreach (ParameterInfo opInfo in opParamInfo)
{
      opKVP = opDictionary[opInfo.Name];

      switch (opInfo.ParameterType.FullName)
      {
            case "System.String":
                  opObjects[lpLoop] = opKVP.Value.ToString();
                  break;

            default:
                  opObjects[lpLoop] = opKvp.Value;
                  break;
      }

      lpLoop ++;
}

opDataService.GetType().GetMethod(zpService).Invoke(opDataService, opObjects);