0

I have some data in a JSON file that I need to load into a List. But the "Type" of the List will be known only at runtime as it will be a user input.

E.g. The following de-serialization works.

using (StreamReader sr = File.OpenText(path))
{
     string dataJson = sr.ReadToEnd();
     items = JsonConvert.DeserializeObject<List<Abc>>(dataJson);
}

But it does not work when I try to get "Type" from the user (stored in s). Following code returns a type conversion error.

     string s = "Abc";
     Type model = Type.GetType($"ModelPath.{s}");
        
     var constructedListType = listType.MakeGenericType(model);
     var instance = (IList)Activator.CreateInstance(constructedListType);
     dynamic items;
        
     using (StreamReader sr = File.OpenText(path))
        {
            string dataJson = sr.ReadToEnd();
            items = JsonConvert.DeserializeObject<List<dynamic>>(dataJson);
        }
  • You did not use List here: items = JsonConvert.DeserializeObject>(dataJson); – Sh.Imran Jul 23 '20 at 05:42
  • 2
    99.9345345 times out of 100, of all questions asked on SO, `dynamic` is the **WRONG** approach and creates more problem then it solves. This comment will self destruct – TheGeneral Jul 23 '20 at 05:47
  • There is a [non-generic overload of `JsonConvert.DeserializeObject()`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConvert_DeserializeObject_2.htm) which accepts a `Type`. See the linked duplicate question. – Brian Rogers Jul 23 '20 at 06:54

0 Answers0