1

Good Afternoon Everyone, I am trying to dynamically invoke a function by passing its appropriate parameters. Let's say the function looks like this:

public string CreatePerson(Person p)

Object p is received as Json and I want to deserialize it into the appropriate runtime Type depending on the parameter Type so that I can pass it into the Newtonsoft.Json library function JsonConvert.DeserializeObject (jsonReceived).

Below is my code:

m = this.GetType().GetMethod(method);
List<object> a = new List<object>();
foreach (var param in m.GetParameters())
{
    //have to convert args parameter to appropriate function input
     a.Add(ProcessProperty(param.Name, param.ParameterType, args));

 }

 object invokeResult = null;
 invokeResult = m.Invoke(this, a.ToArray());


private object ProcessProperty(string propertyName, Type propertyType, string    jsonStringObject)
 {
     if (propertyType.IsClass && !propertyType.Equals(typeof(String)))
      {
          var argumentObject = Activator.CreateInstance(propertyType);
          argumentObject = JsonConvert.DeserializeObject<propertyType>(jsonStringObject);
           return argumentObject;
      }
  }

I get the following error :

The type or namespace name 'propertyType' could not be found (are you missing a using directive or an assembly reference?)

Where am I approaching this wrong? How can I get the parameter Type dynamically during runtime so it can handle types other than Person and be able to pass it to DeserializeObject?

2

2 Answers 2

4

The problem is that generics are done at compile time and you only know the type at runtime. Essentially the compiler thinks that propertyType should be a compiled type and not a variable of type Type.

Fortunately there are overloads that will let you do what you want such as DeserializeObject(String, Type)

Use like this:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);
Sign up to request clarification or add additional context in comments.

1 Comment

No problem. You will find that quite often anything generic along these lines has an overload like this. And hopefully you understand a bit more about generics now so you can see why this problem happens and know that you should look for alternatives (like other overloads) if you come across something similar. :)
3

You cannot use a runtime System.Type propertyType as a type parameter to a generic method. Instead, use the overload of DeserializeObject that takes a runtime type:

argumentObject = JsonConvert.DeserializeObject(jsonStringObject, propertyType);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.