Blazar Blazar - 1 month ago 9
JSON Question

C# Creating generic List from JArray

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>>();

The compiler states I'm using a variable as a type. Which makes sense, but can't find a way around it.

Any help would be appreciated!

dbc dbc
Answer Source

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 List<>, 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 Type.

  • 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 BusinessObjects.Contact.