1

I can only write this in pseudo-code since I don't know the correct syntax.. If there is one.

I have a method I want to call:

JsonConvert.DeserializeObject<Type>(string value);

Which would return the given type.

The problem is that I don't know how to pass the type to that method since I won't know the type at build time. The method from my MVC Controller would be:

public JsonResult Save(string typeName, string model)
{
    // Insert your genius answer here.
}

I need to have my type later on so I can use a DataContractSerializer to store it.

Any help would be appreciated.

James South
  • 10,147
  • 4
  • 59
  • 115
  • possible duplicate of [How to use reflection to call generic Method?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal Jan 17 '14 at 16:31

2 Answers2

1

If you don't know the type at compile time, then you'll have to use the Reflection API to invoke the method.

This has been answered before, see Jon's Skeet's answer on this question for example.

Community
  • 1
  • 1
Paul Ruane
  • 37,459
  • 12
  • 63
  • 82
  • I really didn't know exactly how to word what I was looking for so I couldn't find previous examples. The link was very useful... Thanks! – James South Aug 23 '11 at 13:05
1

You can use the Type.GetType() method. It has an overload that accepts a string of the assembly-qualified name of the type, and returns the corresponding Type.

Your code would look something like this:

public JsonResult Save(string typeName, string model)
{
    // My genius answer here
    Type theType = Type.GetType(typeName);
    if (theType != null)
    {
        MethodInfo mi = typeof(JsonConvert).GetMethod("DeserializeObject");
        MethodInfo invocableMethod = mi.MakeGenericMethod(theType);
        var deserializedObject = invocableMethod.Invoke(null, new object[] { model });
    }
}
dlev
  • 48,024
  • 5
  • 125
  • 132
  • I had to loop through the methods using `GetMethods()` to avoid an ambiguous match exception and the final line should have been `var deserializedObject = invocableMethod.Invoke(null, new object[] { model });`. Got it working though so thanks very much!! – James South Aug 23 '11 at 13:04
  • 1
    Since there are two DeserializeObject methods, one generic and another that isn't, running the code results in an exception, "Ambiguous match found." Instead, you can try invoking the method that accepts value and type var method = typeof(JsonConvert).GetMethod("DeserializeObject", new[] {typeof(string), typeof(Type)}); var command = method.Invoke(null, new object[] {json, contentType}); – wonster Mar 16 '17 at 22:29
  • @wonster although i wished to use that make generic method one, yet thanks – Hassan Faghihi Jul 01 '18 at 12:30