I have a C# .Net class RootObject which contains a number of lists of various object types. I get a json object from an ajax call and deserialize it into a RootObject instance. I would like to iterate over all the lists in my root object and create data tables for them to pass to a stored procedure, but I can't figure out how to do that. Can anyone help?
public class RootObject
{
public List<Car> Car { get; set;}
public List<Plane> Plane { get; set;}
public List<Train> Train { get; set;}
}
/// <summary>
/// Returns a data table filled with the values from the input list
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="list"></param>
/// <returns></returns>
public DataTable CreateDataTable<T>(IEnumerable<T> list)
{
Type type = typeof(T);
var properties = type.GetProperties();
DataTable dataTable = new DataTable();
foreach (PropertyInfo info in properties)
{
dataTable.Columns.Add(new DataColumn(info.Name, Nullable.GetUnderlyingType(info.PropertyType) ?? info.PropertyType));
}
foreach (T entity in list)
{
object[] values = new object[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
values[i] = properties[i].GetValue(entity);
}
dataTable.Rows.Add(values);
}
return dataTable;
}
/// <summary>
/// This function saves the layout specified by the the user with the ID specified
/// </summary>
/// <param name="encryptedBEMSID"></param>
/// <param name="Layout"></param>
/// <returns></returns>
public string Save(string encryptedBEMSID, string Layout)
{
// Make a list of table variable parameters to hold the results of the deserialization
List<SqlParameter> parameters = new List<SqlParameter>();
// Deserialize the json object
RootObject obj = JsonConvert.DeserializeObject<RootObject>(Layout);
PropertyInfo[] objLists = obj.GetType().GetProperties();
foreach (PropertyInfo pi in objLists)
{
string ObjectType = pi.Name; // This would be "Car", "Plane", or "Train"
string UpperObjectType = ObjectType.ToUpper();
// HERE'S WHERE I NEED HELP! I'd Like to replace Car with the class specified by ObjectType
List<Car> List = obj.Car;
DataTable dt = CreateDataTable<Car>(List);
// do stuff with the resulting data table
}
}
EDIT TO ADD JSON
{
"Car": [
{"name": "The General", "color": "red"},
{"name": "Batmobile", "color": "blue"}
],
"Plane": [
{"name": "Air Force One", "color": "white"},
{"name": "Spirit of St. Louis", "color": "gray"},
{"name": "Wright Flyer", "color": "brown"}
],
"Train": [
{"name": "Orient Express", "color": "black"},
{"name": "Ye Olde Bullet Train", "color": "orange"}
]
}