Hesam Kashefi Hesam Kashefi - 2 months ago 34
C# Question

Deserialization of Json using reflection in C#

I want to use the following Method with reflection using Newtonsoft.Json:

MyType object = JsonConvert.DeserializeObject<MyType>(jsonString);


This is my approach that doesn't work (ambiguous match exception) :

Type type = Type.GetType("MyType",false);
Type JSONCovert = typeof(JsonConvert);
MethodInfo deserializer = JSONCovert.GetMethod("DeserializeObject", new Type[] { typeof(String) });
deserializer = deserializer.MakeGenericMethod(type);
var o = deserializer.Invoke(null, new object[] { JsonString });

Answer

You are getting ambiguous match exception, because there are two methods in JsonConvert, which match the name and parameter types you provided. Those are:

  • public static object DeserializeObject(string value)
  • public static T DeserializeObject<T>(string value)

You have to be more specific to select correct method. Unfortunately, you will not be able to do that using GetMethod - instead you will have to scan the methods list and fine the correct one. You can do it like this:

    var JSONCovert = typeof(JsonConvert);
    var parameterTypes = new[] { typeof(string) };
    var deserializer = JSONCovert.GetMethods(BindingFlags.Public | BindingFlags.Static)
        .Where(i => i.Name.Equals("DeserializeObject", StringComparison.InvariantCulture))
        .Where(i => i.IsGenericMethod)
        .Where(i => i.GetParameters().Select(a => a.ParameterType).SequenceEqual(parameterTypes))
        .Single();

EDIT: One more thing I can clarify is: remember that your approach will result in o being of type object. You will not be able to cast it to MyType in compile-time.