I'm working on a dynamic import proces from Json to object array.
Getting a little bit stuck by creating a List<> based on a string reference to the class object.
I'm importing json data from a REST server and using a business objects list to map the json data to predefined classes that can be configured. I'm using NewtonSoft.Json for the parsing of the data to classes.
string classname = "BusinessObjects.Contact";
Type classtype = Type.GetType(classname);
// ... filled jsonstring from api request
string json = ""; // json filled from rest request
JObject obj = JObject.Parse(json);
JArray array = (JArray)obj["contacts"];
// the issue part...
var records = array.ToObject<List<classtype>>();
Rather than deserializing your
JArray, you could access it dynamically as shown in Querying JSON with dynamic. But if you would prefer to deserialize to a fixed list type, since you are writing non-generic reflection-based code, you can do:
var listType = typeof(List<>).MakeGenericType(classtype); var records = array.ToObject(listType);
Given an open generic type such as
Type.MakeGenericType() creates a closed generic type by substituting the
Type argument(s) for the type parameters of the open type.
JToken.ToObject() is a non-generic version of
ToObject() that can deserialize to a specified
Once you have created your
records list you can cast it to the non-generic
IList interface to access collections items.
Sample fiddle with prototype sample JSON and definition for