De-serialize JSON into a List using a runtime Class

32 Views Asked by At

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);
        }
0

There are 0 best solutions below